C# Interface Inheritance to Abstract class
Here:
public class ConreteFunctionality:AbstractFunctionality
{
public void Method()
{
Console.WriteLine("Concrete stuff" + "\n");
}
}
... you're not overriding the existing method. You're creating a new method which hides the existing one. (You should get a warning, too, suggesting the use of the new
modifier if you really want this behaviour.) The interface was implemented in AbstractFunctionality
, so the interface mapping table refers to the method in that class.
Now if you reimplement the interface:
public class ConcreteFunctionality : AbstractFunctionality, IFunctionality
... then the interface mapping will refer to the method in ConcreteFunctionality
and you'll get the behaviour you expect for the call through the interface (i.e. your third call) but you'd still get the implementation in AbstractFunctionality
for your second call.
It would be generally cleaner and more sanity-preserving to make the method in AbstractFunctionality
virtual, and override it in ConcreteFunctionality
. That way it will use the ConcreteFunctionality
implementation in all cases.
You need to define classes as:
public abstract class AbstractFunctionality:IFunctionality
{
public virtual void Method()
{
Console.WriteLine("Abstract stuff" + "\n");
}
}
public class ConreteFunctionality:AbstractFunctionality
{
public override void Method()
{
Console.WriteLine("Concrete stuff" + "\n");
}
}
As you have not overriden Method() in ConreteFunctionality, the run time environment executes Method() associated with AbstractFunctionality object as it cannot apply dynamic polymorphism here. Introducing virtual
and override
makes the run time environment to execute the overriden method in child class.
You are missing virtual
and override
keywords. Without this you don't get virtual functions.
You can mark Method
in AbstractFunctionality as virtual
and mark the Method
in ConreteFunctionality
as override
. As mihirj has shown.
Similar issues tackled in - Why are C# interface methods not declared abstract or virtual?