Extension Methods in C# 3.0 - C# Tutorials and Examples

Extension Methods in C# 3.0 - C# Tutorials and Examples

by David Hayden ( Sarasota Florida Web Design ), Filed: C# 3.0

 

Last night I was reading an eBook, called LINQ for Visual C# 2005, that talked not only about LINQ, but a number of new features in C# 3.0 that make LINQ possible.

One of the new features coming in C# 3.0 ( and VB9 ) 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); } }

 

Cool stuff.

 News Feed: David Hayden ( Sarasota Florida Web Design )

Filed: C# 3.0

posted on Thursday, November 30, 2006 10:04 PM

My Links

Post Categories

Article Categories

Archives

Loose-Leaf Tea