I have run into a problem with generics and new members. I wrote a generic class which operates on an object of type ObjectA. ObjectB derives from ObjectA and hides a few of ObjectA’s members. When I supply the type of ObjectB as the type parameter to the generic class, I would expect that when I call any of the members hidden by ObjectB, I would be calling ObjectB’s implementation. However, the CLR still calls the hidden members (ObjectA’s implementation). This seems illogical because I explicitly provided the type of ObjectB to the generic class. Is this a problem with generics themselves, or am I doing something wrong?
Edit: Unfortunately, I do not have access to ObjectA’s source code and the member I want to override is not virtual. If I had access to ObjectA’s source code, I would make the member virtual, but as I cannot do so, my only option for ‘overriding’ the member is through the ‘new’ keyword.
class GenericClass<T> where T : ObjectA { public void DoWork(T item) { // When type parameter 'T' is ObjectB, should get ObjectB's implementation item.Invoke(); } } class ObjectA { public void Invoke() { // A's implementation... } } class ObjectB : ObjectA { public new void Invoke() { // B's implementation... } } static void Main() { GenericClass<ObjectB> genericClass = new GenericClass<ObjectB>(); ObjectB objectB = new ObjectB(); genericClass.DoWork(objectB); }
No. The calls generated by the compiler are to the members it knows about at compile-time. That’s the members exposed by
ObjectA.Any reason you’re not using normal inheritance, with virtual/overridden methods?
Here’s another example of the same kind of thing, by the way – the overloaded == operator for strings isn’t used, even though
Tisstringin the call toFoo: