-1

I have the following interface:

interface MyInterface {
   void Method1(string someArg);
   void Method2(int anotherArg);
}

I have some arbitrary amount of implementations of this interface, I want to loop through them all and invoke method[x] with a given argument.

I could do this with a loop, such as:

foreach (var myImplementation in myImplementations)
{
   myImplementation.Method1("ok");
}

But, assuming this were in a private method, how can I pass the Method1("ok"); part as an argument itself?

private void InvokeSomething(/*which arg here?*/)
{
    foreach (var myImplementation in myImplementations)
    {
       myImplementation /* how can I make this part implicit? */
    }
}

Please assume there are many methods, and there are many implementations (i.e. I want to avoid a switch or an if here)

JᴀʏMᴇᴇ
  • 218
  • 2
  • 15
  • 1
    `InvokeSomethingOnInterface(Action action) => action()`, what have you tried? – CodeCaster Jan 07 '21 at 12:24
  • 1
    If you search "C# pass interface method as parameter", which appears to be your actual question, you'll find plenty of hits. My point was: have you tried anything like _that_? I'm not asking that for the sake of asking that, I'm asking it to find out whether you have found anything and it didn't work. – CodeCaster Jan 07 '21 at 12:28
  • Half of the battle of knowing how to search for something is knowing how to word your search, I wasn't aware it would be the method that was being passed as a parameter. You've assumed I've known more about the solution than I did. – JᴀʏMᴇᴇ Jan 07 '21 at 12:30
  • 1
    It's literally in your question: "how can I pass the [method call] part as an argument", and if you search the web for that, you'll find plenty of hits. Happy to help. – CodeCaster Jan 07 '21 at 12:30

1 Answers1

0

You need a lamda expression as an argument:

private void InvokeSomething(Action<MyInterface> action)
{
    foreach (var myImplementation in myImplementations)
    {
         action.Invoke(myImplementation);
         // or: action(myImpelementation) - the ".Invoke" is optional.
    }
}

which can be called as follows:

InvokeSomething(i => i.Method1("ok"));
Heinzi
  • 167,459
  • 57
  • 363
  • 519