C# 9.0 Covariant return types - Overridden virtual function - TypeLoadException
Description
C# 9.0 Overridden virtual function works fine when the return type is a covariant derived type, however it fails when the return type is a covariant derived type that contains the overridden function.
Code Snippet
`using System;
class A
{
public virtual A VirtualMethodA() => new();
}
class B : A
{
// C# 9.0 Covariant return types
/*
C# 9.0 Overridden virtual function can return a type derived from the return type declared in the base class method
*/
// Fails:
public override B VirtualMethodA() => new();
// Works:
// public override C VirtualMethodA() => new();
}
class C : A { }
class Program
{
static void Main()
{
B b = new();
b.VirtualMethodA();
Console.WriteLine("Hello, World!");
}
}`
Error
$ dotnet --version
5.0.100-rc.1.20452.10
$ dotnet run
Unhandled exception. System.TypeLoadException: Could not load type 'B' from assembly 'Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
at Program.Main()
Test.exe - Application Error
The exception unknown software exception (0xe0434352) occurred in the application at location 0x00007FFE88BC3B29.
OK Cancel
C# 9.0 Covariant return types - Overridden virtual function - TypeLoadException
Description
C# 9.0 Overridden virtual function works fine when the return type is a covariant derived type, however it fails when the return type is a covariant derived type that contains the overridden function.
Code Snippet
`using System;
class A
{
public virtual A VirtualMethodA() => new();
}
class B : A
{
// C# 9.0 Covariant return types
/*
C# 9.0 Overridden virtual function can return a type derived from the return type declared in the base class method
*/
// Fails:
public override B VirtualMethodA() => new();
// Works:
// public override C VirtualMethodA() => new();
}
class C : A { }
class Program
{
static void Main()
{
B b = new();
b.VirtualMethodA();
Console.WriteLine("Hello, World!");
}
}`
Error
$ dotnet --version
5.0.100-rc.1.20452.10
$ dotnet run
Unhandled exception. System.TypeLoadException: Could not load type 'B' from assembly 'Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
at Program.Main()
Test.exe - Application Error
The exception unknown software exception (0xe0434352) occurred in the application at location 0x00007FFE88BC3B29.
OK Cancel