==
for object
will always mean: reference equality. For a reference, the default is always null
, so if !prop.PropertyType.IsValueType
, then you only need a null
check. For value-types, you will be boxing. So reference equality will always report false, unless they are both Nullable<T>
for some T
, and both are empty. However, to get a "default" value-type (prop.PropertyType.IsValueType
), you can use Activator.CreateInstance(prop.PropertyType)
. Just keep in mind that ==
is not going to do what you want here. Equals(x,y)
might work better.
Getting the default of an unknown type at runtime [duplicate]
-
09-03-2022 - |
Question
I am using reflection to get all the properties of an object. I then need to see if any of those property’s values are the default of whatever type they happen to be. Below is my current code. It is complaining that the namespace or type could not be found. This leads me to believe that it has something to do with how c# does implicit type coercion. Since I am grabbing the type at run time it does not know how to compare it or something not really clear on that.
I was hoping to avoid a switch case comparing on the name of the type that comes in but right now that is looking like my only option unless the brilliant people on StackOverflow can lead me in the right direction.
private bool testPropertyAttribute(PropertyInfo prop)
{
dynamic value = prop.GetValue(DataObject, null);
Type type = prop.PropertyType;
/* Test to see if the value is the defult of its type */
return (value == default(prop.PropertyType)
}
Solution
OTHER TIPS
You can do this you just cannot rely on the == operator to do the work. You'll want to use .Equals or object.ReferenceEquals to do the comparison.