1

When I'm trying to use Covariance and Contravariance on classes I'm getting an error that variant parameters can be applied only on interfaces and delegates.

// This will compile successfully
interface IInterface<out T>
{
}

// This will produce error at compile time
class MyClass<out T>
{
    
}

For the second case(with classes) Compiler is displaying the below message:

enter image description here

Any idea why C# has such restrictions?

Community
  • 1
  • 1
Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42
  • 3
    https://softwareengineering.stackexchange.com/questions/309955/why-covariance-is-forbidden-for-abstract-class-in-c – Farhad Jabiyev Jan 10 '20 at 15:14
  • Have a look at [msdn](https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance) _In the .NET Framework 4, variant type parameters are restricted to generic interface and generic delegate types._ – Pavel Anikhouski Jan 10 '20 at 15:15
  • You cannot always assume that every feature added to a language is automatically orthogonal across all existing features. Often (Always?) when two features won't work together, it's because they can't work together or they need additional work which is not felt to be worth it. It's not someone going "we'll *restrict* them for working together for " – Damien_The_Unbeliever Jan 10 '20 at 15:20

0 Answers0