Calling Member Methods on null References

6/6/2008

I just learned about an interesting way to use extensions methods. It turns out that even though extension methods appear to be used like member methods they still are, actually, not. Here is an example:

 

class Program

{

    static void Main(string[] args)

    {

        string value = null;

 

        Console.WriteLine("IsNullOrEmpty: " + value.IsNullOrEmpty());

        Console.ReadKey();

    }

}

 

public static class Extensions

{

    public static bool IsNullOrEmpty(this string value)

    {

        return string.IsNullOrEmpty(value);

    }

}

 Which outputs:

IsNullOrEmpty: True

Comments

Kyle LeNeau - 6/11/2008
Is the Extensions class a "special" class then that applies to all object types?
Justin Chase - 6/24/2008
This is a feature of C# 3.0, the class can be called whatever you want but the it must be a "static" class. Using the keyword "this" before the first parameter is what tells the compiler which types this method should be applied to. Then you just need the appropriate "using" statements for the code you would like this to work.

Add A Comment

Your Name:
Your Email:
Text:
Submit

About Me

Me

My name is Justin Chase and I am a software professional in Minneapolis, Minnesota. I work for a software consulting company called Magenic Technologies and I am the lead developer on an open source project called NBusiness.
More ...

Topics