Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does string addition result is so weird?

Tags:

string

c#

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?

like image 421
tanya Avatar asked Aug 28 '19 18:08

tanya


2 Answers

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.)

like image 82
Jon Skeet Avatar answered Nov 15 '22 16:11

Jon Skeet


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);
}
like image 36
DanB Avatar answered Nov 15 '22 16:11

DanB