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?
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...
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With