Search code examples
c#linqresharpernull-check

Null checking extension method


So, I'm doing a lot of database work in an application - and there are several possible return values of my caching system. It can return null, it can return a default (type) or it can return an invalid object (by invalid object, I mean one with incorrect properties / values). I want to create an extension method to make all those checks for me, like so:

    public static bool Valid<T> (this T obj) where T: class
    {
        if (obj == null) 
            return false;
        else if (obj == default(T))
            return false;
        //Other class checks here
        else 
            return true;
    }

The problem is, my compiler is telling me that if (obj == default(T)) will always be false.

Why is that?


Solution

  • Since you have a "class" constraint (where T: class), default(T) is always equal to null. You already have a check for that in the original if statement, so the second case (obj == default(T)) could never be true.