1

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);
        }
    }
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
Petr
  • 7,787
  • 14
  • 44
  • 53

2 Answers2

4

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.

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • My god :D Thank you! Silly me, I was searching what am I missing (just learning this stuff) – Petr Mar 11 '10 at 13:15
0

I think it's because ListBoxItemCollection.Add actually returns an integer. So that would be a Func<string, int>, not an Action<string>.

EDIT: Never mind; I guess since you were using a delegate statement you would have had to use return for it to evaluate as a Func-like object.

Dan Tao
  • 125,917
  • 54
  • 300
  • 447