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

Author: justinmchase

I'm a Software Developer from Minnesota.