Search code examples
c#.netcovariancec#-9.0

c# 9.0 covariant return types and interfaces


I have two code examples:

One compiles

    class C {
        public virtual object Method2() => throw new NotImplementedException();
    }

    class D : C {
        public override string Method2() => throw new NotImplementedException();
    }

Another one does not

    interface A {
        object Method1();
    }

    class B : A {
        public string Method1() => throw new NotImplementedException();
        // Error    CS0738  'B' does not implement interface member 'A.Method1()'. 'B.Method1()' cannot implement 'A.Method1()' because it does not have the matching return type of 'object'.  ConsoleApp2 C:\Projects\Experiments\ConsoleApp2\Program.cs  14  Active

    }

How covariant return types work in C# 9.0 and why it does not work with interfaces?


Solution

  • Whilst covariant return types in interfaces are not supported as of C# 9, there is a simple workaround:

        interface A {
            object Method1();
        }
    
        class B : A {
            public string Method1() => throw new NotImplementedException();
            object A.Method1() => Method1();
        }