I’m using a library that generates a bunch of classes for me.
These classes all inherit from a common base class but that base class doesn’t define a couple methods that are common to all subclasses.
For example:
SubClassA : BaseClass{ void Add(ItemA item) {...} ItemA CreateNewItem() {...} } SubClassB: BaseClass{ void Add(ItemB item) {...} ItemB CreateNewItem() {...} }
Unfortunately, the base class doesn’t have these methods. This would be great:
BaseClass{ // these aren't actually here, I'm just showing what's missing: abstract void Add(ItemBaseClass item); // not present! abstract ItemBaseClass CreateNewItem(); // not present! }
Since there is a common base class for my A+B objects and a common base class for the Item objects, I had hoped to benefit from the wonderful world of polymorphism.
Unfortunately, since the common methods aren’t actually present in the base class, I can’t call them virtually. e.g., this would be perfect:
BaseClass Obj; Obj = GetWorkUnit(); // could be SubClassA or SubClassB ItemBaseClass Item = Obj.CreateNewItem(); // Compile Fail: CreateNewItem() isn't in the base class Item.DoSomething(); Obj.Add(Item); // Compile Fail: Add(...) isn't in the base class
Obviously casting would work but then I’d need to know which type I had which would negate the benefits.
How can I ‘force’ a call to these methods? I’m not worried about getting an object that doesn’t implement the method I’m trying to call. I can actually do what I want in VB–I don’t get intellisense but the compiler’s happy and it works:
CType(Obj, Object).Add(Item) // Note: I'm using C#--NOT VB
Againt, I have no control over these classes (which I think rules out partial classes).
You cannot call a non-virtual method of a derived class without resorting to reflection or other dirty tricks. If you want to do it, it’s easy then: