Search code examples
c#anonymous-functionanonymous-methods

Passing in an anonymous method/function as a parameter in C#


I have a method that needs to conditionally execute a method, something like this:

int MyMethod(Func<int> someFunction)
{
    if (_someConditionIsTrue)
    {
        return someFunction;
    }

    return 0;
}

I want to be able to pass a Linq query in to MyMethod as someFunction:

int i = MyMethod(_respository.Where(u => u.Id == 1).Select(u => u.OtherId));

How do I do this?


Solution

  • int i = MyMethod(() => _respository.Where(u => u.Id == 1).Select(u => u.OtherId));
    

    As you can see, I've made the query into a lambda. You will have to do this because otherwise, your query will be executed just before calling MyMethod (...and will introduce compile-time errors ;) ) and not while it executes.

    A side note:

    This return someFunction; should be return someFunction();.