Tag Archives: Null

C#: Generics and checking for null

When writing C#, in Visual Studio, using generics… have you ever tried checking for null? I have always found that a bit of a hassle.

Say we have this method which returns the subject if it is not null, and the result of a createNew() function if it is null.

public static T NewIfNull<t>(this T subject, Func</t><t> createNew)
    if (subject == null)
        return createNew();
    return subject;

Not claiming this is a very useful method, but it was the simplest thing I could come up with 😛 Anyways, in Visual Studio you will now probably have a blue (is blue here at least) squiggly line under the equality operator. It states you are doing a Possible compare of value type with ‘null’, which of course is reasonable and correct. We could just ignore it and move on… but we don’t really like squiggly lines, do we? I sure don’t… so lets get rid of it.

Continue reading C#: Generics and checking for null