C# Method where constraint T:V

Viewed 73

I have this method:

void SomeMethod<T,V>() where T:V
{
  List<T> listT = getT();
  List<V> listV = listT.ToList<V>()
}

Its says that listT dont contains a ToList() method.

The above implementation doesn't work. But it works with concrete classes, like below:

interface Ifoo{}
class Bar : Ifoo{}

List<Bar> bar = getBar();
List<Ifoo> bar2 = bar.ToList<Ifoo>()

Why is that? How can I make the method works with those generics constraint?

1 Answers

The reason why bar.ToList<Ifoo>() works is because the compiler can be assured Bar implements Ifoo.

However, when you are in the generic context, even with the constraints that T is V the compiler cannot resolve the extension method (even though we assume it should be capable of it).

It's likely you just want to use Cast... Assuming T can be cast to V:

Casts the elements of an IEnumerable to the specified type

Example

List<V> listV = getT().Cast<V>().ToList();
Related