Answer: 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