Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't using FieldInfo.SetValue to set a ValueType to null fail?

(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?

like image 616
Sebastian Good Avatar asked Aug 25 '10 06:08

Sebastian Good


1 Answers

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.

like image 55
Rob Avatar answered Oct 10 '22 15:10

Rob