Extension methods allows developer to add extra method to an existing class without creating a derivative of it or without modifying the original class code. Lets take an example of the standard C# library String class. We want to add a method to validate if the string length is zero or not. An extra method can be added to this class by simple implementing a method using extension method syntax. Extension method signature looks like this :
{
methods body
}
So in our example of string class if we add a method called IsZero to return true when check passed; it will look like
public static bool IsZero( this string thisObj )
{
return thisObj.Length== 0;
}
The 'this' word before the first parameter in the method identifies which class this method relates to. In this case it's string class.A working example is as follows.
=====================
====================
=====================
using System.Collections.Generic;
namespace ConsoleApplication1
{
public static class Program
{
private static void Main(string[] args)
{
var postcode = "SL2 8FF";
var flag = postcode.IsPostcode();
// var costs = new List();
// var sum = costs.
}
}
static class Extension
{
///
/// An extension method to String class to check whether this string is a postcode.
///
///
///
public static bool IsPostcode(this string input)
{
return false;
}
///
/// And extension method to List to return sum of all entry of the list
///
///
///
public static double Sum( this IList inputList )
{
var sum = 0.0;
foreach( var item in inputList )
sum += item;
return sum;
}
}
}
====================
Few points to remember:
- Extension method implementer class has to be static class.
- All extension methods must be static
Advantage:
No comments:
Post a Comment