StreamWriter writing a text file's content incorrectly

I am using the StreamWriter class to write some text to a newly created text file, but the output is always weirdly wrong, this is my code:

StreamWriter sw = new StreamWriter("newtextfile.txt", false, Encoding.Unicode);
for (int d = 0; d < count; d++)
{
    sw.WriteLine(d + '^' + str1[d] + '^' + str2[d] + '^' + str3[d]);
}
sw.Flush();
sw.Close();

the output goes like this(this is the start of the file):

65342STR1^STR2^STR3
65343STR1^STR2^STR3

...etc

I have no idea why is the WriteLine skipping the d + '^' and writing that random number.

Jon Skeet
people
quotationmark

The problem is that this expression:

d + '^'

doesn't involve any strings. It's trying to add an int and a char, which it does by promoting the char to int (which will have a value of 65342, because that's the UTF-16 code unit for '^'), and then performing normal numeric addition. The result (an int) is then being converted to a string due to the subsequent + operator with str1[d] as its right-hand operand.

You could use string literals instead:

d + "^" + ...

but I would personally use formatting instead:

sw.WriteLine("{0}^{1}^{2}^{3}", d, str1[d], str2[d], str3[d]);

That's simpler to read, in my view.

people

See more on this question at Stackoverflow