Programming - C# Extension Methods


Extension methods are a new feature added to the C# specifiation. They allow you to dynamically add methods to classes from the context of your own application. It is especially usefull for code re-usability and keeps messy static and instance oriented functions to their variable scope.

An example would be to add a regular expresion extension directly to the string class.

You could do this within an extension implementation in the following way:

static class Program

{

static void Main(string[] args)

{

string s = "Hello, world";

s.Strip(@"<(.|\n)*?>");

}

/// <summary>

/// Strips text according to the regular expression passed in

/// </summary>

/// <param name="s"></param>

/// <param name="expresssion"></param>

/// <returns></returns>

static string Strip(this string s, string expresssion)

{

Regex.Replace(s, expresssion, string.Empty);

}

}


As you can see, we have added an extension method, which is a string utility dirctly to the class instance. Because it is defined in the scope of our application it is only available to ourselves.

and

Home | Privacy Policy | Site Map | Links | Company | Contact Us | Arena           

We provide cutting edge software development, consultancy and web design services            

There are currently 656 user(s) with 40775 hits.