LPeter1997
✅ Return List<Entity> from method with return type of List<T> where T : Entity
(A relevant, decent piece of doc: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/variance-in-generic-interfaces)
55 replies
✅ Return List<Entity> from method with return type of List<T> where T : Entity
In that case, I'd do this:
You can also store the lists as
object
and then instantiate them as List<T>
, cast them as such when accessing them. I personally like that less 😄55 replies
✅ Return List<Entity> from method with return type of List<T> where T : Entity
The problem is, you instantiated a
List<Entity>
. Let's assume you want to promise it only stores some derived type T
of Entity
and you lend it out as List<T>
. The problem is, internally this could have contained any Entity
, you can not be sure it's not just T
s in there, breaking the type system55 replies
✅ Return List<Entity> from method with return type of List<T> where T : Entity
What you are asking for here is not unheard of, it's called variance, when
T<U>
can become T<V>
in some cases where U
and V
are in some relation (based on the nature of the relation this is either called co- or contravariance)55 replies