Generic property- specify the type at runtime
Posted
by Lirik
on Stack Overflow
See other posts from Stack Overflow
or by Lirik
Published on 2010-05-20T08:46:13Z
Indexed on
2010/05/20
8:50 UTC
Read the original article
Hit count: 294
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?
© Stack Overflow or respective owner