Reputation: 2400
I'm aware of inheritance with classes (obviously) but I want to know if the behaviour can be replicated within functions?
I have a situation where all methods need to implement some logic before being called, and rather than duplicate the code across all functions, I want to know if there's some way to inherit a base function or something similar that executes before the rest of the function processes?
Is this possible with C#?
For example, I have the following methods:
public void MyFunction1 {
if(debug)
return;
MyProductionApi.DoSomething();
}
public void MyFunction2 {
if(debug)
return;
MyProductionApi.DoSomethingElse();
}
As you see from above, my scenario basically involves checking whether I'm in development so I can avoid expensive 3rd party API calls. I just want to skip over them if I'm testing, but want to avoid writing a check for each method as there are a large number of functions.
Ideally I could create some base functionality that executes the check that I can inherit from, but I don't know if this is possible?
Upvotes: 0
Views: 143
Reputation: 11389
I want to know if there's some way to inherit a base function or something similar that executes before the rest of the function processes?
You don't need necessarily inheritance to solve the problem of repeating the code. You could also pass the function as parameter to an other function, doing some basic jobs before calling it. You can do it like
public void MyFunction(Action a)
{
if(debug)
return;
a();
}
and call it like
MyFunction(MyProductionApi.DoSomething);
This solves your scenario of
I just want to skip over them if I'm testing
in a very simple way without complicated structures or inheritance.
Upvotes: 5