2

Take this example.

MessageBox.Show("You cannot create an incident and also provide a Case Number\nPlease choose one or the other");

I would like to have it on two lines like this, but without the + operator

MessageBox.Show("You cannot create an incident and also provide a Case Number\n" + 
                "Please choose one or the other");

But I was wondering "is there some escape character where I can do it without the string concatenation?"

Niels
  • 48,601
  • 4
  • 62
  • 81
patrick
  • 16,091
  • 29
  • 100
  • 164

4 Answers4

3

You can do this (note you cannot indent the second line or the indentation will become part of the string):

MessageBox.Show(@"You cannot create an incident and also provide a Case Number
Please choose one or the other");

But in reality you should not worry about using the + string concatenation as the compiler will optimize it away.

Community
  • 1
  • 1
lc.
  • 113,939
  • 20
  • 158
  • 187
3

You could make it a verbatim string:

string msg = @"You cannot create an incident and also provide a Case Number
Please choose one or the other";
MessageBox.Show( msg );
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    That will add an extra new line, and cause the second line to be indented quite a bit. – Jon B Dec 10 '12 at 15:33
1

Here you go

MessageBox.Show(@"You cannot create an incident and also provide a Case Number 
Please choose one or the other");
Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39
-2

Use the following:

MessageBox.Show(string.Format("This is my first line. {0} This is my second line. {0}" +
    "And this is my third line.", Environment.NewLine));

Remember, this only works in certain scenarios. For instance in HTML you'd need to use <br /> instead of Environment.NewLine, but the system is the same.

Isaac Llopis
  • 432
  • 5
  • 12
  • IMHO this is even uglier, will definitely be a performance hit, and *still* doesn't get rid of the concatenation. – lc. Dec 10 '12 at 15:33
  • In that case follow the answer of @tim-schmelter, but that does *only* work on Windows machines with Windows Forms' MessageBoxes. The solution I propose can be used also with strings on a .resx file, supplying what the character of NewLine is in every application, such as if you use the same message both in Web and Desktop, for instance. – Isaac Llopis Dec 12 '12 at 10:49
  • @IsaacLlopis. Only works in messageboxes? It's a string literal, it will work wherever it's in scope. – Tony Hopkinson Dec 14 '12 at 21:56
  • Environment.NewLine is not a
    for instance. If you plan to use the same text for a Web application, \n characters will not be rendered properly because those are not proper formatted New Lines for HTML.
    – Isaac Llopis Dec 18 '12 at 12:44