What is Extension Methods in C# 3.0?

Developer code for assemblies. Compile it & publish it for client use. User of assembly may like to have some additional functionality in data types of the assembly. e.g int or Int32 do not have function to convert integer to complex number. ComplexNumber is the new data type defined by user.

Now with C# 3.0 has provided with the concept of extension methods. Extension methods enable us to extend the functionality of data types already defined. No source code of the assembly is available to modify & recompile the assembly. Still one can extend the data types functionality.

Inheritance also provides capability to extend the functionality but the extended functionality is available only for derived classes & not to the base class. e.g Consider I'd like to have a ToInt function in String class. If I use inheritance approach, I have to create new derived type. So I cannot use methods of derived type on my String objects.

Extension methods are written in static class. The method should also a static method. First parameter of the method must be of type being extended. The first parameter must have this keyword before it.

See the code below.

public static class ExtensionInt
{
public static Complex ToComplex(this int val)
{
Complex temp = new Complex();
temp.Real = val;
return temp;
}
}

Complex is the type defined as follows:

public class Complex
{
public int Real;
public int Imag;
public override string ToString()
{
return (Real.ToString() + "+i" + Imag.ToString());
}
}

Use the method ToComplex for int or Int32.
static void Main(string[] args)
{
int i = 5;
Console.WriteLine(i.ToComplex().ToString());
}

Sealed classes can take advantage of extension methods. LINQ makes use of extension methods defined in Enumerable static class. The class extends functionality of objects implementing IEnumerable interface. To use the extension methods from Enumerable class refer the assembly System.Core.

No comments:

Post a Comment