See the following code:
public abstract class Base
{
public virtual void Foo<T>() where T : class
{
Console.WriteLine("base");
}
}
public class Derived : Base
{
public override void Foo<T>()
{
Console.WriteLine("derived");
}
public void Bang()
{
Action bang = new Action(delegate { base.Foo<string>(); });
bang(); //VerificationException is thrown
}
}
new Derived().Bang();
throws an exception. Inside the generated CIL of the method Bang
I got:
call instance void ConsoleApp.Derived::'<>n__FabricatedMethod1'<string>()
and the signature of the compiler generated method:
method private hidebysig
instance void '<>n__FabricatedMethod1'<T> () cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void ConsoleApp.Base::Foo<!!T>()
IL_0006: ret
}
I think the correct code should be '<>n__FabricatedMethod1'<class T>
. Is it a bug?
By the way, without using delegate{ }
(lambda expression is the same), the code works fine with syntax sugars.
Action good = new Action(base.Foo<string>());
good(); //fine
EDIT I'm using VS2012 RTMRel in windows8 RTM, .net framework 4.5
EDIT This bug is now fixed.
[IL]: Error: [ConsoleApplication3.exe : ConsoleApplication3.Derived::<>n__FabricatedMethod1[T]][ offset 0x00000001] Unable to resolve token. 1 Error(s) Verifying ConsoleApplication3.exe
– Firebugbase
method calls in delegates (I haven't checked), but even then, the lack of a proper diagnostic is a missing desirable feature in the compiler. (Do report it to Microsoft, of course.) – Robiniawhere T : class
constraint from the virtual method. The code verifies, and runs correctly. – Firebugwhere T : struct
also fails, butwhere T : IComparable
orwhere T : Base
works. Edit:where T : new()
also fails. – FirebugBadImageFormatException
and MS claims it has been fixed. – Chops