tanya
tanya

Reputation: 79

Why does string addition result is so weird?

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?

Upvotes: 5

Views: 296

Answers (2)

DanB
DanB

Reputation: 2124

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);
}

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1500923

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

Upvotes: 9

Related Questions