tags:

views:

37

answers:

1

(related to http://stackoverflow.com/questions/3049477/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?

+1  A: 

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.

Rob