views:

174

answers:

2

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#?

A: 

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
+1  A: 

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
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