Question

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?

Was it helpful?

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.

OTHER TIPS

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).

The first decision you need to make is: Can T be a value type like int?
If so you can remove

 where T: class

and

if (obj == null) return false;
else 

If T is always a reference type you can remove

if (obj == null) return false;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top