5
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?

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
tanya
  • 79
  • 5

2 Answers2

9

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

Asons
  • 84,923
  • 12
  • 110
  • 165
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
7

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);
}
DanB
  • 2,022
  • 1
  • 12
  • 24