Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a generic way to call another method whenever a method is called in C#

I have a method something like this:

public Something MyMethod()
{
    Setup();

    Do something useful...

    TearDown();

    return something;
}

The Setup and TearDown methods are in the base class.

The problem I'm having is that I have to write this type of method over and over again with the Setup() and TearDown() method calls.

EDIT: The tricky part of this method is that "Do something useful..." is specific to this method only. This part is different for every method I create.

Also, I can have MyMethod2, MyMethod3, in a single class. In all cases, I would like to run the setup and teardown

Is there an elegant way of doing this without having to write this every single time?

Perhaps I'm delusional, but is a way to add an attribute to the method and intercept the method call, so I can do stuff before and after the call?

like image 575
Steven Avatar asked Dec 23 '15 13:12

Steven


People also ask

How do you call a method from another?

We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.

How do you call a method from another class without creating an object in C#?

You just need to make it a static method: public class Foo { public static void Bar() { ... } } Then from anywhere: Foo.

How do you call a method from another class main in C#?

You can also use the instance of the class to call the public methods of other classes from another class. For example, the method FindMax belongs to the NumberManipulator class, and you can call it from another class Test.

Is method call in same method?

Yes you can. It is called recursion .


2 Answers

Just implement this method in abstract base class like this:

public Something MyMethod()
{
    Setup();

    DoSomethingUsefull();

    TearDown();

    return something;
}

protected abstract DoSomethingUsefull();

Now you need to override only one method in inherited classes - DoSomethingUsefull()

This is Template Method pattern

like image 91
Dzianis Yafimau Avatar answered Sep 22 '22 16:09

Dzianis Yafimau


Use generics, lambdas and delegates like so:

public SomeThing MyMethod()
{
    return Execute(() =>
    {
        return new SomeThing();
    });
}


public T Execute<T>(Func<T> func)
{
    if (func == null)
        throw new ArgumentNullException("func");

    try
    {
        Setup();

        return func();
    }
    finally
    {
        TearDown();
    }
}
like image 25
Aaron Carlson Avatar answered Sep 22 '22 16:09

Aaron Carlson