ExtensionMethods – flavorful syntactic sugar

A potential place to use an extension method cropped up in our team this week, and I gave feedback that I’d like to avoid it (for this case) because in this scenario, it enabled something that just felt wrong to me – working instance methods off null instances. 

Remember, null in C# isn’t like Ruby’s nil – in the typical case, you’d get a NullReferenceException (like if the below snippet had called GetType() instead of GetName()).

It’s not a big deal, just a funny little thing.  If you don’t use extension methods, of course, then you won’t see this :)

public static class ExtensionMethods
{
    public static string GetName(this Program prog)
    {
        return "oooooooooooohhhhhhhh";
    }
}
public class Program
{
    static void Main(string[] args)
    {
        Program prog = null;
        System.Console.WriteLine(prog.GetName());
    }
}
About these ads