0

I'd like to do something like the following in C#:

    class Container {
        //...
        public void ForEach(Action method) {
            foreach (MyClass myObj in sequence) myObj.method();
        }
    }

    //...
    containerObj.ForEach(MyClass.Method);

In C++ I would use something like std::mem_fun. How would I do it in C#?

Martin Stone
  • 12,682
  • 2
  • 39
  • 53

2 Answers2

2

This ought to work, in C# 3.0:

class Container 
{        
//...        
public void ForEach(Action<MyObj> method) 
{            
    foreach (MyClass myObj in sequence) method(myObj);        
}    
}   

//...    containerObj.ForEach( myobj => myObj.Method() );
jlew
  • 10,491
  • 1
  • 35
  • 58
  • Thanks, that does the trick. (Unfortunately it still creates garbage which is why I didn't just return an enumerator, but that's another story.) – Martin Stone Dec 09 '08 at 15:21
0

Assuming that:

    public void ForEach(Action method) {
        foreach (MyClass myObj in sequence) method(myObj);

is no good for you, then I think you're stuck with reflection.

James Curran
  • 101,701
  • 37
  • 181
  • 258