Reputation: 2728
I did not find anything about this exact scenario while googling.
In C# is it possible to allow an abstract method to be implemented in the derived class, but only called in the base class?
The reason I would want to do this is that I want to be able to define multiplier do "do-er" methods if you will, but I want to wrap all the calls to that method in a lock. I don't want to have to leave it up to the method implementor to remember to put locks in their methods, and I don't want them to be able to call the method without a lock.
It's not absolutely necessary to protect it to this level but I thought it would be nice if I could.
Upvotes: 1
Views: 290
Reputation: 11273
You can do this by playing with the access modifiers:
public abstract class BaseClass
{
public void DoSomethingDangerous()
{
lock (someObject)
{
DoDangerous();
}
}
protected virtual void DoDangerous() { }
}
public class ChildClass : BaseClass
{
protected override void DoDangerous()
{
//Do something here
}
}
Since the public
method only exists on the base class, the "unprotected" child method cannot be called directly, this way the base class can control in what context the "doer" method is called.
Really though if you want to protect access to some resource you should lock on the calls to that resource, don't try to force user code to be implemented in a certain pattern. If you need to lock on a dictionary access for example, either use the appropriate type (ConcurrentDictionary
) or set the access to private
and provide getter/setter/deleter methods in the base class and use the locks in there.
Upvotes: 2