I was reading a question on making a generic property, but I'm a little confused at by the last example from the first answer (I've included the relevant code below):
You have to know the type at compile
time. If you don't know the type at
compile time then you must be storing
it in an object, in which case you can
add the following property to the Foo
class:
public object ConvertedValue {
get {
return Convert.ChangeType(Value, Type);
}
}
That's seems strange: it's converting the value to the specified type, but it's returning it as an object when the value was stored as an object. Doesn't the returned object still require un-boxing? If it does, then why bother with the conversion of the type?
I'm also trying to make a generic property whose type will be determined at run time:
public class Foo
{
object Value {get;set;}
Type ValType{get;set;}
Foo(object value, Type type)
{ Value = value; ValType = type; }
// I need a property that is actually
// returned as the specified value type...
public object ConvertedValue {
get {
return Convert.ChangeType(Value, ValType);
}
}
}
Is it possible to make a generic property? Does the return property still require unboxing after it's accessed?