Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PropertyInfo SetValue and nulls

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?

like image 419
Nelson Rothermel Avatar asked Jun 15 '10 22:06

Nelson Rothermel


1 Answers

If you have the PropertyInfo, you can check the .PropertyType; if .IsValueType is true, and if Nullable.GetUnderlyingType(property.PropertyType) is null, then it is a non-nullable value-type:

        if (value == null && property.PropertyType.IsValueType &&
            Nullable.GetUnderlyingType(property.PropertyType) == null)
        {
            throw new InvalidCastException ();
        }
like image 196
Marc Gravell Avatar answered Sep 29 '22 08:09

Marc Gravell