Reputation: 6120
I would like to explain main problem with example.
public class BaseClass
{
public virtual void Add()
{
Console.WriteLine("Add call from BaseClass");
}
public virtual void Edit()
{
Console.WriteLine(" Edit call from BaseClass");
this.Get();
}
public virtual void Get()
{
Console.WriteLine(" Get call from BaseClass");
}
}
public class DerivedClass:BaseClass
{
public override void Add()
{
Console.WriteLine(" Add call from DerivedClass");
base.Edit();
}
public override void Edit()
{
Console.WriteLine(" Edit call from DerivedClass");
}
public override void Get()
{
Console.WriteLine(" Get call from DerivedClass");
}
}
And called like
DerivedClass d = new DerivedClass();
d.Add();
The result :
But I want to get the result as :
When derived class calls its own Add method, Add method calls base class EDit method. When base class edit method called from derived class it calls get method of the derived class. but I want to call base class's get method. How can I achieve this?
Upvotes: 1
Views: 177
Reputation: 660032
How can I achieve this?
If you don't want virtual dispatch then don't dispatch a virtual method. Dispatch a non-virtual method. That implies that a non-virtual method must exist, so let's write one. Then it becomes obvious how it must be called:
public class BaseClass
{
public virtual void Add() { ... }
public virtual void Edit() { this.BaseGet(); }
public virtual void Get() { this.BaseGet(); }
private void BaseGet() { ... }
}
That's how do to what you want, but the more important question here is why do you want to do this thing? There is probably a better way to design your class hierarchy, but without knowing more about what you are really trying to do, it is hard to advise you.
Upvotes: 6