Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous function not returning the correct string

I have the following piece of code:

delegate string CD();
void MyFunction()
{
    stringBuilder.Append((CD)delegate()
    {
        switch(whatever)
        {
            case 1 : return "A";
            ...
            default: return "X";
        }
    });
}

But the stringBuilder appends text MyNamespace.MyClass+CD instead of A or X. Why does this happen?

like image 358
karel Avatar asked Oct 25 '11 08:10

karel


1 Answers

Because StringBuilder.Append calls ToString on the argument you provided. As far as this is a delegate casted as CD, it returns it's type.

To have the values A or X returned, the delegate has to be invoked. But Append does not expect a delegate and therefore it won't invoke it.

like image 74
PVitt Avatar answered Oct 13 '22 02:10

PVitt