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>(); 
+43
generics inheritance c # extends
Jan 19 2018-11-11T00:
source share
4 answers

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.

+66
Oct 11 2018-11-11T00:
source share

See Covariance and Contravariance with .Net 4.0 . But it only works with interfaces right now.

Example:

 IEnumerable<Base> list = new List<SubClass>(); 
+7
Jan 19 2018-11-11T00:
source share

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 .

+4
Jan 19 2018-11-11T00:
source share

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; 
0
Jul 29 '15 at 1:05
source share



All Articles