I’ve got an interface with a several methods in it.
interface IMyInterface
{
//...
void OnItemClicked()
//...
}
And an implementation
class MyClass : IMyInterface
{
//Other methods
public void OnItemClicked(){ /*...*/ }
}
Now, I want to have a class that behaves like MyClass except of OnItemClicked(), I want some modifications for this method.
I thought to inherit an override but I don’t want to change the MyClass (like: public virtual void OnItemClicked()…) because its not my implementation,
I don’t want to implement IMyInterface again because the OnItemClicked() is the only part of MyClass to modify.
Do I have any other way to do it?
Since you are implementing an interface, polymorphism is probably something you’d like to keep. It’s impossible to override the method without modyfing the base class with a virtual, so you must use new instead of virtual as Tigran wrote.
This means that writing this kind of code but only the base version of the method would be executed:
To execute the right code you should write ugly code like this:
Anyway there is a way to have your classes executing the right method when they are assigned to variables declared as IMyInterface. The way to go is to explicitly implement the part of the interface that you want to override, in your case the OnItemClicked method. The code is the following:
In this way:
executes the base method
executes the method of the derived class
executes the method of the derived class and is bound at runtime. This means that you can write the code of my initial example like this and have the right methods executed: