KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
If the generic type argument (of either a calling class or calling method) is constrained with where T : Base the new method in T == Derived is not called, instead the method in Base is called. Why is the type T ignored for method call even though it should be known before run time? Update : BUT, when the constraint is using an interface like where T : IBase the method in Base class is called (not the method in interface, which is also impossible). So that means the system actually is able to detect the types that far and go beyond the type constraint! Then why doesn't it go beyond the type constraint in case of class-typed constraint? Does that mean that the method in Base class that implements the interface has implicit override keyword for the method? Test code: public interface IBase { void Method(); } public class Base : IBase { public void Method() { } } public class Derived : Base { public int i = 0; public new void Method() { i++; } } public class Generic<T> where T : Base { public void CallMethod(T obj) { obj.Method(); //calls Base.Method() } public void CallMethod2<T2>(T2 obj) where T2 : T { obj.Method(); //calls Base.Method() } } public class GenericWithInterfaceConstraint<T> where T : IBase { public void CallMethod(T obj) { obj.Method(); //calls Base.Method() } public void CallMethod2<T2>(T2 obj) where T2 : T { obj.Method(); //calls Base.Method() } } public class NonGeneric { public void CallMethod(Derived obj) { obj.Method(); //calls Derived.Method() } public void CallMethod2<T>(T obj) where T : Base { obj.Method(); //calls Base.Method() } public void CallMethod3<T>(T obj) where T : IBase { obj
Tags (comma-separated)
Save Edits
Cancel