Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenating an action with a string using dynamics

Tags:

c#

c#-4.0

I have the following code in C#:

Action a = new Action(() => Console.WriteLine());
dynamic d = a;
d += "???";
Console.WriteLine(d);

and the output is

System.Action???

while if you add an int instead of a string to d it would throw an exception.

Can you please explain why does this happen?

like image 741
Orlando William Avatar asked Nov 10 '11 22:11

Orlando William


2 Answers

I think this happens because when you use d += "???"; d is converted to string (using default ToString() method which takes object name) and then "???" is appended and wrote to console.
If you try to use d += 2 this fails because there's no default way to convert an Action to an integer. Same for other types...

like image 119
Marco Avatar answered Sep 30 '22 08:09

Marco


Adding a string to anything in .NET will cause that thing's .ToString method to be called, and treat the addition as a string concatenation. The same thing would happen if you weren't using a dynamic.

Action a = new Action(() => Console.WriteLine());
Console.WriteLine(a + "???"); // outputs "System.Action???"

Any Action will return System.Action when its .ToString method is called.

The only difference between += in the original example and the + in this example is that you are setting the result of the concatenation into the dynamic variable. It would be equivalent to:

object a = new Action(() => Console.WriteLine());
a = a + "???"; // The same as: a = a.ToString() + "???";
Console.WriteLine(a);
like image 24
StriplingWarrior Avatar answered Sep 30 '22 09:09

StriplingWarrior