Extension Methods in 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.

by David Hayden

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

6 Responses to Extension Methods in C# 3.0

  1. dhayden says:

    Compile time.

    If during compilation the compiler cannot find a valid method or method extension of the method being invoked, you will get an error.

    If I remove the IsValidEmailAddress Extension Method shown above, I will get a compile time error telling me that string does not have a method IsValidEmailAddress.

  2. chris donnan says:

    This is pretty cool stuff. It looks sort of C++ like to me. Like an implicit ‘this’ pointer and some functions defined somewhere else…. In C++, they are associated with the class by the :: scope operator… Here it looks like they are implicitly bound to the class scope at run time??

    Good post – I haven’t gotten my 3.0 shoes on yet.

    -Chris

  3. johnpapa says:

    As cool as LINQ is, these new features that are used to support it are even cooler. Nice post.

  4. dhayden says:

    Yep. It only calls my method since the current string.IsNullOrEmpty() method is a static method and extension methods are instance methods.

    The instance method does get called when the string instance is null. I stepped through the debugger with the code shown above and it works.

  5. Justin says:

    Actually it wouldn’t call both it adds the method as a member method to string, the current .net framework IsNullOrEmpty method is a static member for string so you will now have both like this:

    string s = “test”;
    bool a = test.IsNullOrEmpty();
    bool b = string.IsNullOrEmpty(s);

    They will not both be called. Ironically though, this isn’t a great example because if the string is actually NULL then you won’t be able to call this method since its a member method (I could be wrong about that but I’m pretty sure that’s true). A better example might be a serialization example:

    public static byte[] Serialize(this object obj)
    {
    using(MemoryStream ms = new MemoryStream())
    {
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, obj);
    return ms.ToArray();
    }
    }
    public static object Deserialize(this byte[] Serialized)
    {
    using (MemoryStream ms = new MemoryStream(Serialized))
    {
    BinaryFormatter bf = new BinaryFormatter();
    return bf.Deserialize(ms);
    }
    }

  6. Brian Schmitt says:

    Quick Question:
    If I create an extension like your example of the IsNullOrEmpty, does it still call the actual 2.0 IsNullOrEmpty method in addition to the newly created one? Or does it ONLY call your new method? If both, Is there a order of precedence?

    Seems like some great potential and abuse if it does call both.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>