What is extension method in C#?

 Posted by SheoNarayan on 12/22/2008 | Category: C# Interview questions | Views: 20064

This is a new feature in C# 3.0. This method allows us to add a new static method to the existing classes.

For example, if we want to validate an Email address using the static method of the string class (built-in) class, we can add an extension method like this.

public static bool IsValidEmail(this string input)

Regex regEx = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
return regEx.IsMatch(input);

Notice the parameter passed to above method. Here "this" indicates the string class. Now, we can use above extension method like this.

string myEmail = "me@me.com";

bool IsValidEmailAddress = myEmail.IsValidEmail();

In this case as the format of the email id in myEmail variable is correct so IsValidEmailAddress will be true.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Raja on: 12/26/2008
Very good explanations Sheo. Thanks for sharing your knowledge.

Posted by: Naraayanan on: 6/27/2012 | Points: 10
Hi Shoe,
Thanks for Sharing your knowledge.I found this Error "'string' does not contain a definition for 'IsValidEmail' and no extension methodIsValidEmail' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) " when i was using your Code in .Net Framework 3.5. Please tell me how to solve this .
Posted by: Chvrsri on: 6/27/2012 | Points: 10
Hi Naraayanan,

Thank you so much for responding but can you post the same question in forum section?

Here only responses are allowed but not questions. Thank you for your co-operation.

Login to post response