Search code examples
c#delegatesactionanonymous-methods

Action<T> vs anonymous method question


I had a question answered which raised another one, why following does not work? I do not understand it. The compiler says: Cannot convert anonymous method do string. But why?

    public List<string> list = new List<string>();
    private void Form1_Load(object sender, EventArgs e)
    {    
        a.IterateObjects(B);
        // why this does not work:
        a.IterateObjects(delegate(string a) { listBox1.Items.Add(a); });
    }
    private void B(string a)
    {
        listBox1.Items.Add(a);
    }
    public void IterateObjects(Action<string> akce)
    {
        foreach (string a in list)
        {
            akce(a);
        }
    }

Solution

  • You have some variable confusion. a is already declared elsewhere, so change:

    a.IterateObjects(delegate(string a) { listBox1.Items.Add(a); }); 
    

    to:

    a.IterateObjects(delegate(string s) { listBox1.Items.Add(s); }); 
    

    and it should work fine.