I'm a newbie in C# programming, and I don't understand how character escaping works. I tried many of them, but only '\t' works like it should. An example for my code:
textBox1.Text = "asd";
textBox1.Text = textBox1.Text + '\n';
textBox1.Text = textBox1.Text + "asd";
MultiLine is enabled, but my output is simply "asdasd" without breaking the line. I hope some of you knows what the answer is.
You need "\r\n"
for a line break in Windows controls, because that's the normal line break combination for Windows. (Line breaks are the bane of programmers everywhere. Different operating systems have different character sequences that they use as their "typical" line breaks.)
"\r\n"
is two characters: \r
for carriage return (U+000D) and \n
for line feed (U+000A). You don't need to do it in three statements though:
textBox1.Text = "First line\r\nSecond line";
Now, I've deliberately gone with \r\n
there instead of Environment.NewLine
, on the grounds that if you're working with System.Windows.Forms
, those will be Windows-oriented controls. It's unclear to me what an implementation of Windows Forms will do on Mac or Linux, where the normal line break is different. (My guess is that a pragmatic implementation will break on any of \r
, \n
or \r\n
, just like TextReader
does, for simplicity.)
Sometimes - such as if you're writing a text file for consumption on the same machine - it's good to use Environment.NewLine
.
Sometimes - such as when you're implementing a network protocol such as HTTP which mandates a specific line break format - it's good to be explicit about it.
Sometimes - such as in this case - it's just not clear. However, it's always worth thinking about.
For a complete list of escape sequences in C#, you can either look at the C# language specification (always fun!) or look at my Strings article which contains that information and more.
See more on this question at Stackoverflow