Zero Validation Test Method

So, I do a lot of work with databases in the application - and there are several possible return values ​​for my caching system. It can return null, it can return a default value (type), or it can return an invalid object (invalid object, I mean one with incorrect properties / values). I want to create an extension method to do all of these checks for me, for example:

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 that my compiler tells me that if (obj == default(T)) will always be false.

Why is this?

+8
c # linq resharper null-check
source share
3 answers

Since you have a class constraint ( where T: class ), default(T) always zero. You already have a check for this in the original if statement, so the second case ( obj == default(T) ) can never be true.

+21
source share

I'm not sure that you limit it to a class because you want it or because you feel what you need. If this is the last, here is a way to check the default values ​​for complex and simple types:

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

If your choice to limit it to a class only was intentional or for a business case, feel free to ignore this offer. Another thing that this may not take into account is the boxing of simple types (although nowadays I usually use simple types with a zero value, for which this code really works).

+1
source share

The first decision you need to make is as follows: Can T - value type, for example int?
If possible, 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; 
0
source share

All Articles