Fun with Extension Methods

Posted Wednesday, June 6, 2007 9:15 AM by C-Dog's .NET Tip of the Day

Since I have Orcas installed, I thought I would give extension methods a try. By now, you have probably heard what they are. They give you the ability to supplement existing objects with your own methods. I'll do a quick example and then I'll tell you about some things I ran into as I was implementing it.

For this example, let's say I want to add a method to int to check if a number is even or not. The first thing to do is create a static class (has to be static and non-generic) along with a static method. The key to telling the compiler that it is an extension method is the use of the keyword this in the parameter list.

namesapce MyExtensions
    public static MyExtensionClass
        public static IsEven(this int myInt)
               return (myInt % 2);

That is all that is necessary to create the extension method. The class can be named anything and is not used in any way, shape, or form when using the extension method. To use the extension method, simply reference the same namespace and use it like it was a native member of int.

using MyExtensions;
int x = 10;
bool isEven = x.IsEven();

That is all there is to it. It will show up in IntelliSense and everything. So in implementing extension methods, so far my general conclusion is that it is best to keep them in their own assembly. The reason being is that I had not luck using an extension method in another class in the same assembly. Another thing to keep in mind is that, you do not have access to the private member varaibles of the object that you are extending in this manner (although you can use any of the public properties).

Another thing to point out is that you can even use extension methods with classes that are sealed. For example I added a method to SqlDataAdapter. Some people may like this. Some may not. Overall, I think extenion methods are pretty neat. I'll be interested in seeing the best practices on when it is appropriate to use them an when it is not.

Read the complete post at