Search code examples
c#methodsdelegatesmem-fun

C# equivalent of C++ mem_fun?


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


Solution

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