Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 322
caesay Avatar asked Feb 08 '12 17:02

caesay


2 Answers

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.

like image 184
Reed Copsey Avatar answered Nov 19 '22 00:11

Reed Copsey


I'm not sure if you are constraining it to class because you want to or because you feel you have to. If it's the latter, here is a way to do default value checking on complex and simple types:

public static bool Valid<T> (this T obj)
{
    return !EqualityComparer<T>.Default.Equals(obj, default(T));
}

If your choice to constrain it to class only was intentional or for a business case, feel free to ignore this suggestion. Another thing this may not account for is boxing of simple types (although I usually use nullable simple types these days, which this code does work for).

like image 27
Brittonlj Avatar answered Nov 19 '22 02:11

Brittonlj