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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: