I’m using reflection to iterate through the properties of objects. For Nullable<> types, the type is being returned correctly using the PropertyType property. However, when I invoke the property getter (either via PropertyType.GetGetMethod().Invoke(obj, new object[0]) or PropertyType.GetValue(obj, null), the result’s type is the unwrapped primitive, not Nullable<>. For reason’s I’d rather not go into, I need to convert this result into its Nullable<> type. This throws an InvalidCastException in such cases:
Convert.ChangeType(property.GetValue(obj, null), property.PropertyType);
Is there another way to ensure the property value’s type is always the same as the property’s type?
You cannot do that in reflection code, because in reflection code you are talking about
object, and there is no such thing as a boxedNullable<T>– it is either the boxed underlying value, or anull.If you know the actual type, you can use the constructor to create a wrapped value, but it must only be assigned to a typed field/variable that is
Nullable<T>– notobject– else the CLI unwraps it again.However, for that same reason, you don’t need it wrapped when using reflection; any code like
SetValuewill acceptobject, and will do the right thing; regardless of whether it isnullor a boxed underlying value, it will be handled correctly.Basically, the CLI has special handling when boxing and unboxing
Nullable<T>that makes the question void.