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.
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#.
It sets the default value for the type. This behavior wasn't mentioned in the documentation before, but now it is:
If this PropertyInfo object is a value type and value is null, then the property will be set to the default value for that type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With