General property - how to specify a type at runtime

I read a question about creating a generic property , but I'm a little confused by the last example from the first answer (I've included the relevant code below):

You must know the type at compile time. If you don't know the compile time type, then you must store this 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);
    }
}

      

It seems strange: it converts the value to the specified type, but returns it as an object when the value was stored as an object. Doesn't the returned object require un-boxing? If so, why bother with type conversion?

I am also trying to create a generic property, the type of which will be determined at runtime:

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);
        }
    }
}

      

Can a generic property be created? Does the return property still need to be unpacked after being accessed?

Note. I don't want to do Foo

generic because I want to Foo

contain values ​​of different types and I want to put different ones Foo

in the collection. In other words, I want to have a collection with different types of objects.

+2


a source to share


1 answer


Convert.ChangeType()

determines the type at runtime. The parameter you give may be calculated at runtime and may not be known by the compiler at compile time.

This is why it should return a generic object and not a specific type.



It still converts the type - for example, from int to double. Compile time type object

, but runtime type changes. If you run GetType()

on this object, you get the actual runtime type.

When you convert a value type to a reference type, you get a box, and vice versa, you get an un-box - so it depends on the types you are using.

+2


a source







All Articles