If I have something like:
object value = null;
Foo foo = new Foo();
PropertyInfo property = Foo.GetProperties().Single(p => p.Name == "IntProperty");
property.SetValue(foo, value, null);
Then foo.IntProperty
gets set to 0
, even though value = null
. It appears it's doing something like IntProperty = default(typeof(int))
. I would like to throw an InvalidCastException
if IntProperty
is not a "nullable" type (Nullable<>
or reference). I'm using Reflection, so I don't know the type ahead of time. How would I go about doing this?
You can use PropertyInfo.PropertyType.IsAssignableFrom(value.GetType()) expression to determine whether specified value can be written into property. But you need to handle case when value is null, so in this case you can assign it to property only if property type is nullable or property type is reference type:
Also, you may find useful Convert.ChangeType method to write convertible values to property.
If you have the
PropertyInfo
, you can check the.PropertyType
; if.IsValueType
is true, and ifNullable.GetUnderlyingType(property.PropertyType)
is null, then it is a non-nullable value-type: