Extension Methods in C#

In this article we will talk about the new feature of C# introduced in .Net 3.0 and available in higher versions.

Sometimes while developing the application we come up with common functions for validations and other repeated functionality which we use in our application at different places by using  that class which contains those functions and then access those functions by defining them with Static keywords.

Extension Methods are special kind of methods which you can use to extend the existing type by creating your own static class. It is similar like extending the existing type by inheriting it into derived class but here you need not to create another class by inheriting specific type.

Below is the basic example which extending the integer and string type.

Steps to implement extended methods are:

1) Create a static class.

2) Create a static methods for extended method.

3) Parameter for the type for the method should be preceded with this keyword.

Example:

class Program
{
    static void Main(string[] args)
    {
            string StrText = "1";
            bool blVar = StrText.IsNumeric();
            int intVar = 10;
            bool blNonZero = intVar.NonZero();
   }
}

public static class MyExtensionMethods
{
     public static bool IsNumeric(this string s)
     {
            float output;
            return float.TryParse(s, out output);
     }
     public static bool NonZero(this int x)
     {
            if (x < 0)
               return false;
            else
               return true;
     }
}
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