I’m looking for equivalent C# code of following line
private List<? extends HotSpot> hotSpots;
Any help is much appreciated.
Depending on exactly what you need, you're probably either looking for:
public class MyClass
{
private IList<HotSpot> hotSpots;
}
or using where
public class MyClass<T> where T : HotSpot
{
private IList<T> hotSpots;
}
Functionally, I'd say the closest is:
IEnumerable<HotSpot> hotSpots;
If the real type of the the enumerable happens to be an IList
, then ElementAt()
and such will be O(1).
As of .NET 4.5, you could also use:
IReadOnlyList<HotSpot> hotSpots;
and use List.AsReadOnly()
to wrap regular lists.
The .NET approach to variance in generics is letting specific interfaces be either covariant or contravariant, and consequently only allow them to define methods with the generic type parameter as the return value only, or only in the argument list. (As opposed to Java where the compiler does these checks in each expression.) My guess is the rationale is that C# implements generics using reification, and a concrete type like List<out T>
can't exist in the type system.