andryuha
andryuha

Reputation: 1606

Possible to cast generic list of type to a generic list of its super type?

trying to do below, but don't know enough about reflection obviously.

Example of what I'm trying to do is, I want to "resolve" a list of JazzDancer into a list of Dancer (which all dancer types inherit from). Want to make sure that if DanceStyle here is Jazz, only JazzDancer type will be in the list of dancers. hope this make sense.

Problem is that it seems that you can't cast List to List.

Is that even possible?

List<Dancer> dancers = TypeNameResolver<Dancer>.ResolveList(DanceStyle, typeof(Dancer));


public static List<T> ResolveList(IDanceStyle style, Type toType)
        {
            Type list = typeof (List<>);
            Type[] pars = { TypeNameResolver<T>.Resolve(style,toType).GetType()};
            List<T> result = (List<T>)Activator.CreateInstance(list.MakeGenericType(pars));
            return result;
        }

public static T Resolve(IDanceStyle style, Type toType)
{
    Assembly a = Assembly.GetExecutingAssembly();
    var typeName = style.GetType().Name + toType.Name;
    var toTypeNameSpace = toType.Namespace;
    return (T)a.CreateInstance(toTypeNameSpace + "." + typeName);
}

Upvotes: 1

Views: 503

Answers (2)

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 121057

You can do it with a Linq query:

dancers = jazzDancers.Cast<Dancer>();

If you need to do some kind of check on each jazzDancer, you just add a Where such as:

dancers = jazzDancers.Where(jd => jd.SomeFiels == Something).Cast<Dancer>();

Upvotes: 1

Heinzi
Heinzi

Reputation: 172468

You don't need reflection for this. LINQ, on the other hand, can help here:

List<JazzDancer> myListOfJazzDancers = ...;
List<Dancer> myListOfDancers = myListOfJazzDancers.Cast<Dancer>().ToList()

Upvotes: 3

Related Questions