Skip to content

Covariant Return crashes on runtime when there is additional abstract class in between not overriding the abstract method. #45053

@pmrogala

Description

@pmrogala

Description

In net 5.0, windows 10x64, Visual Studio 2019 and C#9 the below code will not run and will produce the following error:

System.TypeLoadException: Return type in method 'Application.TB.GetA()' on type 'Application.TB' from assembly 'Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not compatible with base type method 'Application.T`1[System.__Canon].GetA()'.

    public abstract class T<TR>
    {
        public abstract TR GetA();
    }

    // This abstract causes the error - not overriding the base method cause the runtime to crash
    public abstract class TA : T<A> { }

    // This works
    // public abstract class TA : T<A>
    // {
    //  // Overriding in between fixes the problem
    //    public override A GetA() => new ();
    // }
    
     // Overriden here, in the grandson
    public class TB : TA
    {
        public override B GetA() => new ();
    }
    public class A { }

    public class B : A { }

public static class Program
{
        public static void Main(string[] args)
        {
            System.Console.WriteLine((new TB() as T<A>).GetA().GetType().FullName);
        }
}

Regression?

Don't know. It is a new feature for C#.

Other information

Works with Mono (thanks @lambdageek )

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions