Calling Member Methods on null References

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

About these ads

Drop a brain bomb

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s