chhenning
chhenning

Reputation: 2077

How to cast an object to a List

I have an object which is actually a List. I have a string what the element type is but I don't know how to cast the object to a List? Here is some code depicting my problem.

class Data
{
    public int ID { get; set; }
    public List<double> Values { get; set; }
}

static void Main(string[] args)
{
    Data d = new Data() { ID = 69, Values = new List<double>() };
    d.Values.Add(1.0);
    d.Values.Add(2.0);

    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(Data));
    var propInfo = typeof(Data).GetProperties();

    foreach (var p in propInfo)
    {
        var Value = p.GetValue(d, null);
        var Type = p.PropertyType;

        if (Type.IsGenericType && Type.GetGenericTypeDefinition() == typeof(List<>))
        {
            // get the element type of a list
            var ElementType = Value.GetType().GetProperty("Item").PropertyType;

            // how to cast to List< "ElementType" > ???
        }
        else
        {
            types.Add( Type.FullName );
        }
    }
}

Upvotes: 2

Views: 156

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062502

Generics and reflection don't play very nicely. Your best bet is to use the non-generic IList API:

IList list = (IList)Value;

Then you can iterate, access by index, Add, Remove, etc.

Upvotes: 4

Related Questions