infCAT
infCAT

Reputation: 23

Call class method as parameter

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

Upvotes: 0

Views: 515

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239636

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

Upvotes: 8

Related Questions