Extension method is new language element added to C# 3.0
Extension methods allow developers to extend the existing CLR types with methods of their own.
Without extension methods the same goal can be achieved by sub-classing the original type and adding the required method to the subclass.
However, with this approach we can invoke the newly added method only on subclass, and not on base class. But extension methods make it possible to add new method to a CLR type without having to sub-class the CLR type.
To understand how exactly the extension method works, we will develop a small code snippet to validate a US Zip Code.
To validate a zip code in C# 2.0, following is one of the possible approach:
class Validator
{
public static bool IsValidZip(String USZipCode)
{
return Regex.IsMatch(USZipCode,@"^(\d{5}-\d{4}\d{5}\d{9})$^([a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d)$");
}
}
To use this validation logic, the caller code could be
string zip = "12345";
if(Validator.IsValidZip(zip) == true)
{
//Actions
}
Now, we will implement the same functionality using extension method.
We will create an extension method named IsValidUSZipCode.
public static class Validations
{
//Extension method
public static bool IsValidUSZipCode(this string USZipCode)
{
return System.Text.RegularExpressions.Regex.IsMatch(USZipCode,@"^(\d{5}-\d{4}\d{5}\d{9})$^([a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d)$");
}
}
Please note the “this” keyword in parameter. It instructs the compiler to treat the method IsValidUSZipCode as extension method.
So far the code is very similar to C# 2.0 implementation.
The major difference is in the code for utilizing this extension method.
The extension methods are accessed directly from the CLR type.
So in this case, the method IsValidUSZipCode can be accessed right from String type.
To use extension method we just defined, we will simply add a using statement as follows:
using Validations;
Now, to validate zip code, add following code:
string zip = "12345";
if(zip.IsValidZip() == true)
{
//Actions
}
Note that we are invoking the extension method directly on the string type variable.
This is how C# 3.0 extension methods can be defined and used.
Wednesday, December 5, 2007
Subscribe to:
Post Comments (Atom)
1 comment:
Great ! Thanks for putting it together.
Post a Comment