Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to show a newline within a MessageBox

Tags:

c#

newline

I often display messages using MessageBox.Show("This is my message");.
Sometimes I need a newline within a longer text. Usually I use a variant which put one string per line:
MessageBox.Show("Line1" + Environment.NewLine + "Line2" + Environment.NewLine + "Line3");
But I don't like the "overhead". So I found the following solution:
MessageBox.Show(string.Format("Line1{0}Line2{0}Line3", Environment.NewLine));
Is there a better solution with less overhead?

like image 618
Michael Hutter Avatar asked Sep 03 '25 17:09

Michael Hutter


1 Answers

You have pretty much found both ways to do it. A third one would be with string interpolation (to avoid the "extra" string.Format call.

$"Line1 {Environment.NewLine} Line2 {Environment.NewLine} Line3"

Fiddler example: https://dotnetfiddle.net/16Wy57

The string.Format way is pretty much the example at the official format docs

I prefer interpolation as it avoids the extra function in my code, but really it all comes down to preference.

There really is no "overhead" in any of the options, as the operation is trivial and at the end of the day, you concatenate strings.

like image 199
Athanasios Kataras Avatar answered Sep 05 '25 07:09

Athanasios Kataras