Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior when setting value types to null using reflection, why?

Tags:

c#

reflection

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.

like image 846
Mikael Sundberg Avatar asked Dec 06 '22 05:12

Mikael Sundberg


2 Answers

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#.

like image 153
Neil Barnwell Avatar answered Jan 01 '23 11:01

Neil Barnwell


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.

like image 45
Meta-Knight Avatar answered Jan 01 '23 10:01

Meta-Knight