Steven
Steven

Reputation: 766

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?

Upvotes: 5

Views: 2747

Answers (2)

Aaron Carlson
Aaron Carlson

Reputation: 5762

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();
    }
}

Upvotes: 2

Dzianis Yafimau
Dzianis Yafimau

Reputation: 2016

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

Upvotes: 8

Related Questions