How to create and use Extension Methods in C#

As I promised in my previous post, here’s a simple example to create and use extension methods. Extension methods are a powerful feature introduced in Dot Net 3.0/3.5 that allow us to inject/add a custom method in any existing type (even if the type is Sealed/NotInheritable). Lets say, we want to add a new method IsPrime to the existing int (System.Int32) type, then we need to write an static method in an static class like this:

 public static class MyExtensions
    {
        public static bool IsPrime(this int integer)
        {
            //implementation here
            return true;
        }
    }
 

Now, this IsPrime method will be associated with every int type in our project, as depicted in the following screenshot:

Extension Method Demo

Thats all. I just wanted to demonstrate extension methods using a very basic example; if you need more information, try msdn or google.