Home
 
  

Extension Methods

March 11, 2014

Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. (Source MSDN)

For creating Extension method

  1. Method should be in static class
  2. Method should be static
  3. Pass parameter (with this keyword) of type for which you are writing extension method.
  4. Namespace (where extension method defined) should be added where you want to use it

let understand with example

public static class NumericExtension
{
public static ToInt(this string value)
{
int number;
if(int.TryParse(value,out number))
{
return number;
}
else
{
throw new InvalidCastException();
}
}
}

We can use this on string object directly like

class Program
{
static void Main(string[] args)
{
string strnumber ="1980";
int number = strnumber.ToInt(); // call ToInt() directly like member methods
}
}

Extension method behave like public member so it is inherited to derived classes le understand one example.

public static class ObjectExtension
{
public static bool IsNotNull(this object value)
{
return value!=null;
}
}

In above example I attached a extension methods to Object and Object is parent class of all classes, so we can call IsNotNull method on any type.

class Program
{
static void Main(string[] args)
{
string name = null;
//on string type
if (name.IsNotNull())
{
// do your stuff
}
//on string array type
if (args.IsNotNull())
{
//do your stuff
}
List<int> series = new List<int>();
//on generic list type
if (series.IsNotNull())
{
//do your stuff
}
}
}
Govind Malviya

Govind Malviya

Director of Product Development @LoginRadius

 

© 2020