views:

393

answers:

2

I see the signature is:

public virtual void SetValue(object obj, object value, object[] index)

Wouldn't this method cause the parameters to be boxed and unboxed?

Why wasn't this method designed to be generic? Then it could even be inferred by the compiler with no boxing/unboxing penalty at runtime.

+7  A: 

If it were generic, to call the method the type would need to be known at compile time; which would defeat the purpose of using reflection. So yes, this can mean boxing might occur, but object is the only safe type available for this method.

Timothy Carter
+6  A: 

This is partly due to the fact that PropertyInfo.SetValue predates generics - reflection has been part of .NET since the beginning.

However, using generics would be difficult in this specific case, in any manner. There is no way for the compiler to infer this information, as you suggested, since the property info is gleaned at run time, not compile time. That is the purpose behind Reflection.

Instead of trying to work this into a generic method (which would probably have to lead to a non-generic implementation, in any case, due to the runtime behavior), the CLR team made sure that all objects, including value types, work as a System.Object. Yes, this causes boxing, but with reflection's overhead, the small extra overhead of boxing a value type is not really worrisome.

Reed Copsey
Btw I don't quite understand why the type is unknown at compile time for this case? Is it because if you have List<T>, it can be List<int>, List<List<string>>, etc which would be different types?
Joan Venge
Well, if all you have is property info, you can completely get this information at runtime from any type. You don't even need to know what it is - For example, I've done things where I just look for the "ID" property on a specific instance of a class (which has a type that I don't even know - it can be any type, or maybe just something that implements an interface)... Look at the property grid - it works on ANY type, completely at runtime.
Reed Copsey
Thanks Reed. .
Joan Venge