0

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?

4
  • 5
    Why not have these defined in an interface with two implementations. One actually doing the job and the other doing nothing. Then you just need a mechanism to take the right implementation depending on the context when initialising the objects that will use it Commented Aug 22, 2017 at 18:14
  • 2
    Consider aspect-oriented programming, I can imagine adding an attribute [DontRunInDebug] to your method which would inject if (debug) return for you. Commented Aug 22, 2017 at 18:17
  • 1
    in addition to @ Michał Żołnieruk, for example, in our project we use Castle.Proxy Commented Aug 22, 2017 at 18:19
  • There's no good way to do this without using code generation. Commented Aug 22, 2017 at 18:25

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@litelite: This avoids repeating it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.