Home > OS >  C# String joining adding random numbers
C# String joining adding random numbers

Time:04-06

I'm trying to append to my string a number and a newline character, but when I do that the number is different and the newline character is gone. MRE below:

using System;
                    
public class Program
{
    public static void Main()
    {
        string s = "";
        s  = 9   '\n';
        
        Console.WriteLine(s);
        
    }
}

Expected output: 9\n

Actual output: 19

CodePudding user response:

I'm answering this question because I was lost for a good hour trying to figure out what was causing this.

It comes down to the char '\n'. When the line s = 9 '\n'; is run, c# interprets the between 9 and '\n' as an integer addition, in doing so implicitly converting '\n' to it's integer form of 10 (all characters have an integer value, a for example is 97). So what is effectively being run is: s = 9 10;, which is why the final output is 19.

If '\n' is instead a string: "\n", the code runs as expected and the final result is 9\n.

So just be careful with chars in c#, as they will be converted to integers if possible.

CodePudding user response:

Replace your '\n' to Environment.NewLine, this should work.

  • Related