Skip to main content

Extension Methods

It's been a while working on Visual Studio 2008 but there are new features I still didn't use. Extension method is one of them.Extension methods, are a way to call static method by an instance using instance method syntax. There are occasions when you call static methods where you pass an instance as first parameter.
for e.g:
We often copy arrays as
Array.Copy(source,destination....);
would not it be more readable if we can invoke it like
source.Copy (Destination);
Extension methods make it possible.

But example above has hardly anything to do with the word 'Extension'. So, the main idea of a extension method is to enable developers to write a method outside its class definition (of course on requirement basis) and use it just like any instance method.

Let's say I want to extend functionality of an existing type string.
I want to add a new method IsValidPinCode, just like IsNullOrEmpty or any other pre-defined methods.I can do it easily by "EXTENDING" the type string.
For this I have to write a static method outside definition of the type.

public static bool IsValidPinCode(this string s)
{
bool isValid = false;
// your logic to check whether an address is valid
// and assign ‘isValid’ accordingly

return isValid;
}
This method must be a defined inside a static class. Note that keyword this is being used in a static method.This would be signature of an extension method. Type for which it has been extended should be preceded in parameter list with this keyword. Once I define it, I can use it all across my code. (of course within the visibility of class where this method was defined)

string str = "500082";
bool isValid = str.IsValidPinCode();

I think it could be handy sometimes but it is not something I would go about as a language feature.

Comments