In this following example dynamic data type is behaving in a contradictory manner. Please explain the reason.
Dynamic data type multiplying two variables in the 1st output and adding two variables in the 2nd output. Problem is highlighted.
using System;
class Program
{
static void Main(string[] args)
{
dynamic d1, d2;
d1 = "A";
d2 = 1;
Console.WriteLine(d1 + d2);//A1
d1 = 10.01;
d2 = 1;
Console.WriteLine(d1 + d2);//11.01
Console.ReadKey();
}
}
Loading
Posted Apr 23, 2014, 10:43 AM
VulpesPosted Apr 23, 2014, 10:16 AM
When you add an int to a string, you concatenate the string with the 'string value' of the former. In other words, it's like computing "A" + "1" which is "A1".
For the second pair of values, the CLR infers that the type of d1 is double because a double is being assigned to it. As before it infers the type of d2 to be int.
When you add an int to a double, you get a double and the rules of floating point arithmetic therefore give 10.01 + 1 = 11.01.