For the following code:
class B
{
public String G() { return "B.G()"; }
}
class D : B
{
public String G() { return "D.G()"; }
}
class TestCompile
{
private static String TestG<T>(T b) where T: B
{
return b.G();
}
static void Main(string[] args)
{
TestG(new D());
}
}
The result is B.G(), whereas the result of similar C++ code would be D.G().
Why is there this difference?
C# generics are compiled only once: at the time the generic is compiled. (Think about it: C# lets you use
List<T>without seeing its implementation.) Here, it sees from thewhere T: Bclause that the parameter is aB, so it callsB.G.C++ templates are compiled each time they are invoked. When you type
TestG<D>(), a brand new copy ofTestGis compiled withT = D. At invocation time, the compiler sees thatDhas its ownGmethod and calls it.The C++ equivalent of the C# generic would be
The remarks of others regarding the use of
virtualapply equally to C# and C++. I’m just explaining why C++ behaves differently from C#.