C # Java equivalent <? extends Base> in generics
In Java, I can do the following: (suppose Subclass extends Base ):
ArrayList<? extends Base> aList = new ArrayList<Subclass>(); What is the equivalent in C # .NET? Doesn't a keyword exist ? extends ? extends and this does not work:
List<Base> aList = new List<Subclass>(); Actually there is an equivalent (type), the where keyword. I don't know how close it is. I had a function in which I needed to do something similar.
I found msdn page .
I don't know if you can do this inline for a variable, but for a class you can do:public class MyArray<T> where T: someBaseClass
or for the public T getArrayList<T>(ArrayList<T> arr) where T: someBaseClass function public T getArrayList<T>(ArrayList<T> arr) where T: someBaseClass
I did not see it on the page, but using the where keyword it could be possible for a variable.
See Covariance and Contravariance with .Net 4.0 . But it only works with interfaces right now.
Example:
IEnumerable<Base> list = new List<SubClass>(); There is no exact equivalent (since the type system doesnβt work quite like that: erasing styles is all), but you can get very similar functionality with in and out using covariance and contravariance .
If you are looking for two types of generics, take a look at this:
void putAll<K1, V1>(Dictionary<K1,V1> map) where K1 : K where V1 : V;