C# Extension Methods


In this article, let’s know about CSharp Extension methods. Basically this feature was introduced in C# 3.0

Introduction

Extension methods enable you to “add” methods to existing types. They are special kind of static method. They make it possible to extend existing types with additional methods.

Extension methods are declared by specifying this keyword on the first parameter of the methods. Extension methods can only be declared in non-generic, non-nested static classes.

Examples

1. Extend “int” datatype.


public static class MyExtensions
{

  public static bool IsEvenNumber(this int number)

  {
    if (number % 2 == 0)
    {
     return true;
    }
     return false;
  }
 }

To call “IsEvenNumber” extension method from main, consider following code snippet.


class Program
 {
 static void Main(string[] args)
 {
 int i = 45;

 Console.WriteLine(i.IsEvenNumber());
 Console.ReadLine();
 }
 }

 

int-Extension

So in the example above, “IsEvenNumber” has became part of  int datatype and is accessible via intellisense.

2. Extend “string” datatype.


public static class MyExtensions
 {
public static bool IsNullOrEmpty(this string input)
{
if (input == null || input == string.Empty)
{
return true;
}
return false;
}

}

To call “IsNullOrEmpty” extension method from main, consider following code snippet.


class Program
 {
static void Main(string[] args)
{
string str = "";

Console.WriteLine(str.IsNullOrEmpty());
Console.ReadLine();
}
 }

 

string-Extension

So in the example above, “IsNullOrEmpty” has became part of string datatype and is accessible via intellisense.

You can even include the namespance of the Extension methods and reuse them anywhere in your project.

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

Related articles
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s