Wednesday, September 28, 2011

Simple Extension Methods: C# Programming

Simple Extension Methods: C# Programming

1. Create a namespace for the extension methods. (i.e. ExtensionMethods)
2. Cteate a class. (i.e. MyExtensions)
3. Now create the extension methods in the class.

Here, we are extending string type to have a new extension method 'WordCount':

using System;
using System.Text;

namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}


4. Now, lets use this extension method:

using System;
using ExtensionMethods;

namespace ThreadTest
{
class Program
{

static void Main(string[] args)
{
string str = "You are rocking";
Console.WriteLine(str.WordCount());
}
}
}

5. That's it. Happy coding.