December 18, 2007

.Net 3.5 Extensions Part 1

One of the promising features Microsoft released with .net 3.5 is "Extension Methods". As I'm planning to do a series of posts regarding the extensions, here I will start with a simple scenario. First let us see what is this "Extension Methods" is all about.

What is .Net 3.5 "Extension Methods" ?

Extension allow developers to add methods to the existing class/type without wrapping or extending it. It's allow developers to add new methods to an existing CLR type such as string,integer or ICloneable. It even gives the ability to add method implementation on interfaces which I'm planning to cover in my next post.

So let us take a simple scenario and will see how we used to do it.

Requirement is to validate a string to check whether it's a number.

Old way




So here StringHelper is a class where we used to write all our validation methods to an string. So when ever we want to validate we have to call the StringHelper class. Lets see how easy we can do this with extensions.

First you have to write a static class which includes all the validation required to string. I have written IsNumber method by passing the parameter as string. Note that there is this keyword before the type. By doing this we tell the compiler to add this method to the passing parameter type(in this case "string").






so, how do we call this method ? All we have to do is to call the method we wrote in the string variable we defined. You can see there is small blue arrow showing the method is "extension". You can see how easy is to add methods to the existing types without having to call another class to do the job.







You can even write methods with more parameters, below is a simple method which return the character in a string by passing another int parameter




So as we can see here, with extensions we can easily extend the exiting classes in CLR or even our own custom classes/interfaces. In my next post I will show you how we can use the extensions with interfaces. Hope this helps.

2 comments:

Madhawa said...

Good stuffs machan.

Ajeje said...

Very useful, thank you