Saturday, September 28, 2013

"var" keyword and different behavior with "string" data type

This has nothing to do with var, the following code is 100% equivalent to your code and it doesn't use var but it produces the same error and for the same reason:



string x = "ankur";
x = x + 1.0m;
Console.WriteLine(x);
int y = 1;
y = y + "ankur";

The reason is that both expressions (x + 1.0m and y + "ankur") produce a string but the x and y variables have different types. The x variable is of string type so the assignment is valid. But the y variable is of int type so obviously that won't work, you can't implicitly convert a string to a int.


No comments:

Post a Comment