tags:

views:

137

answers:

3

Hello, look at the following example:

public class Test {
    public int Number { get; set; }
    public void TestReflection() {
        Number = 99;
        Type type = GetType();
        PropertyInfo propertyInfo = type.GetProperty("Number");
        propertyInfo.SetValue(this, null, null);
    }
}

In the example I'm setting a int property to null using reflection. I was expecting this to throw an exception because null isn't a valid value for int. But it doesn't throw, it just sets the property to 0. Why!?

Update

Ok, it seems that is just how it is. The property gets the default value of the value-type if you try to set it to null. I have posted an answer describing how I solved my problem, maybe that will help someone someday. Thanks to all who answered.

+7  A: 

It's probably setting values to the default for the type. Bools probably go to false, too, I expect.

Same as using:

default(int);

I found some docs from MSDN the default keyword in C#.

Neil Barnwell
+5  A: 

It sets the default value for the type, as Neil said. Strangely it's not mentioned in the documentation, but in the community content (bottom of the page) this behavior is described:

"For properties that are value types, passing a null reference (Nothing in Visual Basic) for the value parameter sets it to its default value."

Meta-Knight
+1  A: 

The behavior of SetValue (or maybe the default binder) seems a little dangerous, Code equal to this solved my problem:

public class Test {
    public int Number { get; set; }
    public void SetNumberUsingReflection(object newValue) {
        Number = 99;
        Type type = GetType();
        PropertyInfo propertyInfo = type.GetProperty("Number");
     if(propertyInfo.PropertyType.IsValueType && newValue == null) {
      throw new InvalidOperationException(String.Format("Cannot set a property of type '{0}' to null.", propertyInfo.PropertyType));
     } else {
      propertyInfo.SetValue(this, newValue, null);
     }
    }
}

Maybe it will help someone some day...

Mikael Sundberg