Cross posted from http://www.stevenmcd.net/ 

 

Extension methods are something new to the .Net 3.5 framework and an extremely valuable add-on!

Have you ever had a situation where you have been given a sealed class and desperately needed to add a method? Extension methods allow to add your own custom methods to any class! As a small example: imagine to want to add a method to the standard .Net String class. Normally you would never be able to do this.

Lets say we want to add a method to the string class to convert a string to an integer.

Step 1:

Create a Static Class:

namespace ExtensionNamespace
{
public static class Extensions
{
}
}

The reason behind creating a static class is that your functions should always be available without having to instatiate the class in which your methods reside.

Step 2:

Create your static Method:

namespace ExtensionNamespace
{
public static class Extensions
{
public static int ToInt(this string stringName)
{
//declare integer
int _intToReturn = -1;

//convert string to Integer
_intToReturn = Int32.Parse(stringName);

//return integer
return _intToReturn;
}
}
}

The access identifier on the method should always be public and static for the same reasons mentioned above. You need to then specify your return type for this method which in this case would be an "int". The "ToInt" is the my name for this method. when specifying the input parameters for the method you are also specifying which class this method will be extending. Here we are extending the String class. You must *always* prefix the first parameter with the word "this".

Once thats done its up to you to write the code for your method. obviously the code I have written above is extremely basic and so does not follow best practice so pay no attention to it. It is the structure of the method that you should focus on.

Step 3:

Implementing your extension:

When you want to use this extension, simply include the namespace in the code file you're using. So in this case, at the top of your code page, specify the following using statement:

"using ExtensionNamespace;"

Then we simply declare a string for use and view its methods and viola! There it is!
ExtJPG.jpg

 

Cross posted from http://www.stevenmcd.net/