Faqs on asp.net,c#,vb.net and sqlserver2005

this blog covers all the Faqs related to .net technologies like asp.net,vb.net,c#.net,ajax,javascript and sqlserver2005.

Mar 7, 2008

new features in C# 3.0

Extension methods in C# 3.0

One of the new features coming in C# 3.0 is Extension Methods. Quoting from LINQ for Visual C# 2005:
"As the name implies, extension methods extend existing .NET types with new methods."
Extension methods sound like a last resort form of extensibility since they are apparently hard to discover in the code, but nonetheless the idea is cool and could come in handy in the future. Obviously LINQ is handy :)
Most of the examples I have seen pick on the string class, so I won't take this time to be original. Here is an example of adding an IsValidEmailAddress method onto an instance of a string class:

class Program
{
static void Main(string[] args)
{
string customerEmailAddress = "test@test.com";
if (customerEmailAddress.IsValidEmailAddress())
{
// Do Something...
}
}
}
public static class Extensions
{
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
}

The extension methods need to be static methods in a static class within a namespace that is in scope as shown above. The this keyword in front of the parameter string s makes this an extension method.
String.IsNullOrEmpty
One of the coolest things I love about the new string class in .NET 2.0 is the addition of the IsNullOrEmpty method. Now if that wasn't in there, we could do it with Extension Methods. In fact, since IsNullOrEmpty is currently a static method, we can go ahead and add the extension method anyway since it works on class instances. Let's go crazy and have it call Trim(), too :)
class Program
{
static void Main(string[] args)
{
string newString = null;
if (newString.IsNullOrEmpty())
{
// Do Something
}
}
}
public static class Extensions
{
public static bool IsNullOrEmpty(this string s)
{
// Notice I trim it too :)
return (s == null s.Trim().Length == 0);
}
}

Happy Programming

0 Comments:

Post a Comment

<< Home