Wednesday, May 20, 2009

Extension Methods in C#

Today I would like talk about why,how and where abouts of extension methods.

Lets think about the world where we didn’t had Extension methods and how we were coding for the business problems, lets discuss about that with the example

Suppose I have a number which is of type integer and I have to find that, whether the given number is even or not.

Ideal way to program is as shown below.

C# code snippet

Now think of the case, where if you get some thing to check whether the number is even on the given type itself, in this case on int (for example number.IsEven() ) how easy our job would have been.

If you thought about this opportunity, here goes an extension method for you.

Above stuff can be achieved with the extension method concept as shown below..

So cool right?

So now what next, If I have to write my own extension method on a particular type how should I go about it
Rules :
1) I need to have a static classs( Name could be any thing which you wish)
2) I need to have a static method as shown above with the “this” keyword followed by the type to extend.

That’s it!!

Now lets talk about the hidden secret of the Extension method….

Think about the case where we will have both the extension method and instance method on a particular type, on invocation of the method on that type which one will get fired?????

Can you guesss??????

It is the instance method not the Extension Method…..


No comments: