Jamie
Jamie

Reputation: 321

pass a method into another method as a parameter but with parameters

I've posted a similar question (and answered) previously but I've realised I still have a missing piece of the puzzle when passing a method into another method. My question is when passing a method as a parameter how can you include parameters? I've included an example below.

Any help much appreciated.

Many thanks,

Service call

private readonly MemberRepo _memberRepo;

public SomeService()
{
    _memberRepo = new MemberRepo();
}

public string GetMembers(int id)
{
    // This works, i.e. the RunMethod internally calls the Get method on the repo class - problem: how can I pass the id into the repo Get method?
    var result = RunMethod(_memberRepo.Get); 
    ...

    return stuff;
}

private string RunMethod(Func<int, string> methodToRun)
{
    var id = 10;  // this is a hack - how can I pass this in?
    var result = methodToRun(id);
    ..
}

Repository

public class MemberRepo
{
    public string Get(int id)
    {
        return "Member from repository";
    }
}

Update

private string RunMethod(Func<int, string> methodToRun)
{

    if(id.Equals(1))
    {
      // Do something
    //

    var result = methodToRun(id);
    ..
}

Upvotes: 1

Views: 3091

Answers (2)

JLRishe
JLRishe

Reputation: 101652

You can pass a lambda function that performs whatever actions you want:

var result = RunMethod(_ => _memberRepo.Get(10));

This makes the int part of the method signature pretty meaningless, so if you have the ability to change your RunMethod() signature, you can do this:

private string RunMethod(Func<string> methodToRun)
{
    var result = methodToRun();
    ..
}

then this:

var result = RunMethod(() => _memberRepo.Get(10));

Update if you need to be able to access the parameter within your RunMethod() method, then just pass it as a separate parameter as TheLethalCoder suggests:

private string RunMethod(Func<int, string> methodToRun, int id)
{    
    if(id.Equals(1))
    {
      // Do something
    //

    var result = methodToRun(id);
    ..
}

and

var result = RunMethod(memberRepo.Get, 10);

Upvotes: 2

TheLethalCoder
TheLethalCoder

Reputation: 6746

Just pass a second argument to the RunMethod method:

private string RunMethod(Func<int, string> methodToRun, int id)
{
    var result = methodToRun(id);
    ..
}

You can always make id have an optional input as well if needed:

int id= 10

Upvotes: 2

Related Questions