Extension Methods in C#

Extension Methods

There are some function that can be done on a string like String.Split(‘ ‘) ;

To add a new method like that we can go for using a Extension method.

In the following example I have added a new function test.getLength_Ext() to a string.

To do it

1) Create an accessible class with an accessible method

2) Both must be static If not it does not make any difference from creating a class.

3) The parameter(first) must be this followed by the type it must extend. In this case it Extends a string so I use test.getLength_Ext(this String)

public static class a

{
public static int getLength_Ext(this string str)
{
return str.Length;
}
}
class Program
{
static void Main(string[] args)
{
string test = “ABCDE”;
Console.WriteLine(test.getLength_Ext());
Console.ReadLine();
}
}

Hope you Understood . 🙂

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