Posted by: R Manimaran | December 6, 2010

Extensions Method in C# 3.0

Extensions Method in C# 3.0

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Some C# Examples:

public static void UsingExtensionsMethod()
{
     string sampleText = "This is the Sample Text for Extensions Method";
     int count = sampleText.CountWords();
     string mailAddress = "maran@gmail.com";
     bool isValid = mailAddress.IsValidEmailAddress();
}
public static int CountWords(this string input)
{    
    return input.Split(' ').Count();
}

 

If you check, you can see a small arrow in the Method which indicates it is an Extension Method.


public static bool IsValidEmailAddress(this string input)

{

Regex regex = new Regex(@"^[w-.]+@([w-]+.)+[w-]{2,4}$");

return regex.IsMatch(input);

}


If you look the extension method you have a common thing (this string input).The this keyword in front of the parameter string input makes this an extension method.

This Extension method needs to place in a Class which is also static.

In the next article we will create some SharePoint Extensions methods.

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

Categories

%d bloggers like this: