public static void Main(string[] args)
{
int num = 1;
string number = num.ToString();
Console.WriteLine(number[0]);
Console.WriteLine(number[0] + number[0]);
}
I expect the output of 1
and 11
but I'm getting 1
and 98
. What am I missing?
The type of number[0]
is char
, not string
- you're not performing any string concatenation. Instead, you've got a char
with value 49 (the UTF-16 value for '1'). There's no +(char, char)
operator, so both operands are being promoted to int
and you're performing integer addition.
So this line:
Console.WriteLine(number[0] + number[0]);
is effectively this:
char op1 = number[0];
int promoted1 = op1;
char op2 = number[0];
int promoted2 = op2;
int sum = promoted1 + promoted2;
Console.WriteLine(sum);
(It's possible that logically the promotion happens after both operands have been evaluated - I haven't checked the spec, and as it won't fail, it doesn't really matter.)
Because of [], this give the first char of the string.
number[0] + number[0]
is doing 49 + 49 (the ascii code of char 1);
I think you want to do this :
public static void Main(string[] args)
{
int num = 1;
string number = num.ToString();
Console.WriteLine(number);
Console.WriteLine(number + number);
}
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