Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a subclass method on a baseclass object?

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).

like image 659
Michael Haren Avatar asked Nov 08 '25 07:11

Michael Haren


2 Answers

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:

// obj is your object reference.
obj.GetType().InvokeMember("MethodName", 
    System.Reflection.BindingFlags.InvokeMethod, null, obj, null /* args */)
like image 196
mmx Avatar answered Nov 10 '25 00:11

mmx


I might be missing something, but why not make and inherit from an interface with those methods?

If you are in control of the creation process for the instances, you might get what you want by inheriting from the classes which you didn't write and add then interface (no code needs to be written, the compiler will map the interface to the existing non-virtual methods).

like image 21
Lucero Avatar answered Nov 10 '25 00:11

Lucero