C#'s equivalent of Java's <? extends Base> in generics

C#.NetGenericsInheritanceExtends

C# Problem Overview


In Java, I can do the following: (assume Subclass extends Base):

ArrayList<? extends Base> aList = new ArrayList<Subclass>();

What is the equivalent in C# .NET? There is no ? extends keyword apparently and this does not work:

List<Base> aList = new List<Subclass>();

C# Solutions


Solution 1 - C#

Actually there is an Equivalent(sort of), the where keyword. I don't know how "close" it is. I had a function I needed to do something similar for.

I found an msdn page about it.

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 a function
public T getArrayList<T>(ArrayList<T> arr) where T: someBaseClass

I didn't see it on the page but using the where keyword it might be possible for a variable.

Solution 2 - C#

Look into Covariance and Contravariance introduced with .Net 4.0. But it only works with interfaces right now.

Example:

IEnumerable<Base> list = new List<SubClass>();

Solution 3 - C#

There is no exact equivalent (since the type system doesn't work in quite the same way, with type erasure and all), but you can get very similar functionality with in and out using covariance and contravariance.

Solution 4 - C#

If you are looking for two type generics, Take a look at this:

    void putAll<K1, V1>(Dictionary<K1,V1> map) where K1 : K where V1 : V;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLouis RhysView Question on Stackoverflow
Solution 1 - C#RaystormView Answer on Stackoverflow
Solution 2 - C#decycloneView Answer on Stackoverflow
Solution 3 - C#user541686View Answer on Stackoverflow
Solution 4 - C#Guilherme ArgentinoView Answer on Stackoverflow