views:

90

answers:

4

Hello, In the code below I pass method B as an action to be perfomed on on the objects in the IterateObjects method. I would like to ask whether I can explicitly declare the method in the argument instead of passing it by name, something like this:
a.IterateObjects(delegate void(string s){//method body}) Its not correct but I am sure I have seen something like that working. Could you please advise? Thank you

DelTest a = new DelTest(); //class with method IterateObjects
a.IterateObjects(B) //HERE

private void B(string a)
{
    listBox1.Items.Add(a);
}

//another class  ....

public void IterateObjects(Action<string> akce)
{
    foreach(string a in list)
    {
        akce(a);
    }
}
+3  A: 

Yes you can use a lambda like so :

a.IterateObjects ( x => listBox1.Items.Add(x) );
Mongus Pong
A: 

You can declare function B as anonymous function at the point of calling, through a lambda expression.

Franci Penov
A: 

You can use a lambda expression:

a.IterateObjects((string s) => listBox1.Items.Add(s))
klausbyskov
A: 
    delegate void MyFunctionDelegate(string a);

    public void Main()
    {
        iterateObjects (delegate(string a){/*do something*/});
    }

    public void IterateObjects(MyFunctionDelegate akce)
    {
        foreach(string a in list)
        {
            akce(a);
        }
    }

http://msdn.microsoft.com/en-us/library/900fyy8e%28VS.80%29.aspx

that's it :)

remi bourgarel
Yes, this is the way to do it in C# 2
Mongus Pong
Hm but why it doesnt work with Action<T>? The IterateObjects is in different class so I would like to use Action as an argument to pass here
Petr
you can declare your action like this : IterateObjects(new Action<string>(delegate(string a){/*do something*/}));
remi bourgarel