Monday, July 4, 2011

Extension Methods in .NET 3.5

Introduction
Extension method is new to C#.Its allow you to add new method to the existing class.
Description
1.Extension method allows you to add new method to the existing class without modifying the code, recompiling or modifying the original code.
2.Extension method are special kind of static method but they are called using instance method syntax. Their first parameter specify which type the method operate on, and the parameter is precede by “this” modifier.
3.Extension method are only in scope when you explicitly import the namespace into your source code with “using” directive.
For Example in string object there is no method call “Reverse()” function .But if you need to extend the string ….
Sample Code
namespace ExtensionMethods
{
public static class ExtensionsClass
{
public static bool IsValidEmailAddress(this String EmailAddress)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(EmailAddress);
}
}
}

How to Use?
string email = harish@company.com;
if ( email.IsValidEmailAddress() ) {

}
Note how the static method above has a "this" keyword before the first parameter argument of type string. This tells the compiler that this particular Extension Method should be added to objects of type "string".

for more information follow the Link

No comments:

Split the String values with a special character in MS Flow to convert this into Array

 Many times we have a requirement to prepare the Mailing address for some of the documents, suppose there are Address Line1, Address Line2, ...