0

It is possible to do something like this on C#? I want a generic void for calling differents methods from another class.

public class custom{
   public void A(){}
   public void B(){}
}

void doSomething(List<custom> laux, method m ){
    foreach(var aux in laux){
        aux.m; //something like this
    }
}

void main(){
   doSomething(new List<custom>(),A);
   doSomething(new List<custom>(),B);
}
infCAT
  • 23
  • 7
  • 2
    are you talking about delegates, Actions, Func https://learn.microsoft.com/en-us/dotnet/api/system.action?view=net-5.0 ? – demo Jun 15 '21 at 07:32
  • Does this answer your question? [Pass Method as Parameter using C#](https://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp) – Charlieface Jun 15 '21 at 08:31

1 Answers1

8

You can do something close to this via an Action delegate:

void doSomething(List<custom> laux, Action<custom> m ){
    foreach(var aux in laux){
        m(aux);
    }
}

void main(){
   doSomething(new List<custom>(),c=> c.A());
   doSomething(new List<custom>(),c=> c.B());
}
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448