How can C# allow virtual generic methods where C++ can’t allow virtual template methods?

Running this code and analyzing the IL and generated ASM allows us to see what is going on: internal class Program { [MethodImpl(MethodImplOptions.NoInlining)] private static void Test() { var b = GetA(); b.GenericVirtual<string>(); b.GenericVirtual<int>(); b.GenericVirtual<StringBuilder>(); b.GenericVirtual<int>(); b.GenericVirtual<StringBuilder>(); b.GenericVirtual<string>(); b.NormalVirtual(); } [MethodImpl(MethodImplOptions.NoInlining)] private static A GetA() { return new B(); } private class A { public … Read more

Why can this generic method with a bound return any type?

This is actually a legitimate type inference*. We can reduce this to the following example (Ideone): interface Foo { <F extends Foo> F bar(); public static void main(String[] args) { Foo foo = null; String baz = foo.bar(); } } The compiler is allowed to infer a (nonsensical, really) intersection type String & Foo because Foo is … Read more

Assigning List of Integer Into a List of String

You are not getting any compile time error because by using GenericClass<E> in a raw way : GenericClass genericClass = new GenericClass();, you are practically telling the compiler to disable generic type checkings because you don’t care. So the : void genericFunction(List<String> stringList) becomes void genericFunction(List stringList) for the compiler. You can try the following … Read more

Java generic method inheritance and override rules

What we are having here is two different methods with individual type parameters each. public abstract <T extends AnotherClass> void getAndParse(Args… args); This is a method with a type parameter named T, and bounded by AnotherClass, meaning each subtype of AnotherClass is allowed as a type parameter. public <SpecificClass> void getAndParse(Args… args) This is a … Read more