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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With