@
@
@insighter2022-01-19 06:38:20
.NET
@insighter, 2022-01-19 06:38:20

Why is List/IList not covariant?

And the same IEnumerable is covariant. What are the .NET developers guided by in a similar question?

Example

class Program
    {
        static void Main(string[] args)
        {
            List<User> users = null;
            List<Administrator> admins = null;

            users = admins; // ошибка потому что List<T> не ковариантен
            IEnumerable<User> users2 = admins; // ошибки нет т.к. IEnumerable<out T> ковариантен
        }
    }

    public class User { }
    public class Administrator : User { }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2022-01-19
_

They are not variant, because T is accepted as an input (Add), and returned in methods (Get).
And C# in such situations does not allow you to add the appropriate modifiers.
Here with IReadOnlyList there is no such problem because it is covariant.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question