Is there an equivalent in c# for the following code in Java
List<? extends Number> list;
list = new ArrayList<Float>();
list = new ArrayList<Integer>();
list.add(Float.valueOf("4.0")); // doesn't compile and it is fine
Number e = list.get(0); // workds
I was reading about covariant types in c#
List<SomeClass> list2 = new List<SomeClass>();
IEnumerable<Object> list3 = list2; // works
From whatever I understand all the interfaces/classes in Java are supporting covariance by default. Depending on the type parameter used in the declaration, features (method that take the parameterized types as input) that don't follow covariance are not supported. Meaning, List<? extends Number>
can take a reference of List<Integer> or a List<Double>
, but it would no longer support methods like add().
Now, on the other side in C#, looks like I need to find an interface that supports Covariance and then use it. So, whenever I want to write some generic class, I have to write a separate interface that supports all covariant operations for all derived classes and make sure my class implements that interface? Is this correct or am I missing something.
Thanks