0

I have written a piece of code as following:

var i=5;
i='K';

The code is being compiled without an error. As far as my concept is concerned, I cannot re-assign a value in var. Since I have assigned integer 5 to i. the type of i is int. Then why it is allowing to assign a char 'K' in i?

techmad
  • 933
  • 2
  • 11
  • 14

2 Answers2

8

Because a char can be implicitly cast to an int. The type of the variable i would still be int – you can test this using i.GetType() – and its value would be the codepoint of the character 'K' (namely, 75).

In other words, your code is equivalent to writing:

int i = 'K';

“As far as my concept is concerned, I cannot re-assign a value in var.” – That is not correct. You cannot change the type of an implicitly-typed variable (just like you cannot change the declared type of any other variable), but you are allowed to re-assign it another value of the same type (or one that may be cast as so).

Douglas
  • 53,759
  • 13
  • 140
  • 188
0

i is implicitly typed as an integer during your first assignment. Then you are attempting to assign a char value to an integer.

Dave New
  • 38,496
  • 59
  • 215
  • 394