0

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) 

    }
Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
Thinmint
  • 25
  • 2
  • 8
  • [`default` only works with generic parameters.](http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx) Also, your code is missing a closing bracket and a semicolon. – O. R. Mapper Feb 11 '13 at 20:11
  • I assume you expect a non-value type default to be null? – rene Feb 11 '13 at 20:13
  • You should avoid `dynamic` unless you have no other good choice. Using `var` or `object` as the type of `value` would work perfectly well here. – Bobson Feb 11 '13 at 20:15
  • you mean a closing `parenthesis )` – MethodMan Feb 11 '13 at 20:15
  • Sweet thank you it is a duplicate did not see it in my research. Never even thought about doing it that way. – Thinmint Feb 11 '13 at 20:37

2 Answers2

2

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

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.

RayB64
  • 149
  • 1
  • 4