Introduction: C# 3.0 provides a new feature called Extension Methods. Extension methods are methods that can be added to previously defined classes without rebuilding/compiling those classes.
Process: To define an extension method, we first define a static class, Then we define our static method which is meant to be extended. The first parameter of the extension class should be the type of Object we need to extend.
Syntax:
public static (this ) { Do Something ......... ...... return ; }
For Eg:
Suppose we want to extend a method Square() to int type. syntax should be like this:
public static class ExtenderClass { public static int Square(this int num) { return num*num ; } }
Now we can use this method like
static void Main(string[] args) { Console.WriteLine("Enter any Number"); int i=0; i = Convert.ToInt32(Console,ReadLine()); Console.WriteLine("Square of {0} is {1} ",i,i.Square()); }
(NOTE: VS 2008 Intellisense makes “extension methods” visible (see after pressing dot) under the object name just like any other precomiled method available for that object)
Some useful functions:
1. To Check For Null values:
public static bool CheckForNull(this object obj) { if(obj == null) { return false; } else { return true; } }
use this function for any object like:
public void SomeFunction() { If(SomeObj.CheckForNull()) //Check if SomeObje is null or not { //Do Something ..... ..... } }
2> To Cast To Integer Types:
public static Int16 ToShort(this object obj) { Int16 num = 0; Int16.TryParse(obj.ToString(), out num); return num; } public static Int64 ToLong(this object obj) { Int64 num = 0; Int64.TryParse(obj.ToString(), out num); return num; } use this function for any object like: public void SomeFunction() { string strNum="2344"; int i= strNum.ToShort(); long j = strNum.ToLong(); }
(Note: All above mentioned Extension Methods should be defined in a static class.)