(related to PropertyInfo SetValue and nulls)
If I have public class Thing { public int X; }
, a Thing o
, and a FieldInfo fi
that points to the X
field, why is it legal to call fi.SetValue(o, null)
? The runtime sets the field X
to zero, i.e. default(int)
instead of complaining that a ValueType
cannot be set to null
.
Does anyone know the design choice behind this behavior, which at least from C# violates my principle of least astonishment?
The text contained in the Exceptions box for ArgumentException
suggests that the value passed in is subject to conversion, which would explain why it succeeds.
The value parameter cannot be converted and stored in the field.
I do agree that it seems slightly strange, particularly as I generally expect the reflection APIs to be one of the more rigid and less forgiving.
You might try contacting Eric Lippert , whilst this is a BCL/CLR question rather than C#, there's a chance he'll know the answer or know someone who does. Either that or be able to give a very good guess.
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