c# - Check to see if a given object (reference or value type) is equal to its default -
i'm trying find way check , see if value of given object equal default value. i've looked around , come this:
public static bool isnullordefault<t>(t argument) { if (argument valuetype || argument != null) { return object.equals(argument, default(t)); } return true; }
the problem i'm having want call this:
object o = 0; bool b = utility.utility.isnullordefault(o);
yes o object, want make figure out base type , check default value of that. base type, in case, integer , want know in case if value equal default(int), not default(object).
i'm starting think might not possible.
in example, integer boxed , therefore t
going object
, , default of object null, that's not valuable you. if object value type, instance of (which default) use comparison. like:
if (argument valuetype) { object obj = activator.createinstance(argument.gettype()); return obj.equals(argument); }
you'd want deal other possibilities before resorting this. marc gravell's answer brings points consider, full version of method, might have
public static bool isnullordefault<t>(t argument) { // deal normal scenarios if (argument == null) return true; if (object.equals(argument, default(t))) return true; // deal non-null nullables type methodtype = typeof(t); if (nullable.getunderlyingtype(methodtype) != null) return false; // deal boxed value types type argumenttype = argument.gettype(); if (argumenttype.isvaluetype && argumenttype != methodtype) { object obj = activator.createinstance(argument.gettype()); return obj.equals(argument); } return false; }
Comments
Post a Comment