I want to change a function behavior depending how we call the function.
Example:
class A {
public B instance;
public void HWorld(){
Console.WriteLine("Hello from A! \n");
}
}
class B { // No modification allowed.
public void HWorld(){
Console.WriteLine("Hello from B! \n");
}
}
static void Main()
{
B b= new B();
A a= new A();
a.instance = b;
b.HWorld(); // PRINT Hello from B!
a.instance.HWorld(); //PRINT Hello from A!
}
So my question is: Is there a way (with Event Handler
maybe?) to redirect the call B Hworld()
to A Hworld()
when called as an instance of a specific class?
Other information: I know *it's an XY probleme *: there is a better way to design what I want to do. But I still want to know if it's possible, and how to do it (I don't mind if it require destroying c# compiler).
This is a minimal example: As it doesn't represent the reality, and it's more a theorical question, please avoid: "You can call a.HWorld()
".
EDIT
(after on hold) The question I asked was clear. It was an XY probleme, but I was asking for this X question and the topic was closed for Y being unclear (of course, it was not my question). I don't want to debate anymore if there is other way to go around. I'll do an other post for question Y.