Anonymous function does not return the correct string

I have the following code snippet:

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

But stringBuilder adds the text MyNamespace.MyClass+CD instead of A or X Why is this happening?

+6
source share
2 answers

You declared a CD type delegate in your Append call and ToString() is called on it, which returns the default type name, i.e. "MyNamespace.MyClass + CD".

You need to call a delegate to get it for evaluation, for example:

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

Because StringBuilder.Append calls ToString in the argument you provided. Since this is a delegate recorded as a CD, it returns its type.

To return values โ€‹โ€‹of A or X, you must call the delegate. But Append does not expect a delegate and therefore will not call it.

+10
source

Source: https://habr.com/ru/post/900019/


All Articles