I have an asp.net core web application with an abstract class with a virtual method that child classes may or may not override. I want to execute different logic based on whether it was overridden or not and was wondering if the below check is a good idea or not:
public abstract class BaseClass
{
public async Task DoSomethingAsync()
{
var task = OverrideMe();
bool wasOverridden = task != Task.CompletedTask;
await task;
if (wasOverridden)
{
//Virtual method was overridden
}
else
{
//Virtual method was not overridden
}
}
protected virtual Task OverrideMe()
{
return Task.CompletedTask;
}
}
I realize that if the child class returns Task.CompletedTask it would still look like it wasn't overridden. But if we ignore that fact, would this check work? What I'm most concerned about is the Id field of the task. Would that change and maybe cause the equality comparison to fail? When I test my code above it works but what if there are other async tasks running in parallel etc?
CodePudding user response:
What if you set a private field when the method has no overwrite like this:
public abstract class BaseClass
{
private bool _notOverwritten;
public async Task DoSomethingAsync()
{
var task = OverrideMe();
await task;
if (!_notOverwritten)
{
//Virtual method was overridden
}
else
{
//Virtual method was not overridden
}
}
protected virtual Task OverrideMe()
{
_notOVerwritten = true;
return Task.CompletedTask;
}
}
