1

I've recently started learning C#.
I have an string type of variable a.

I'm trying to get a Messagebox to show my variable and some text after it.

MessageBox.Show(a "was your answer"); This doesn't work.
MessageBox.Show(a, "was your answer"); While this throws the text to the title.

How could I make some text appear after the variable, on the same line?

Fedor Hajdu
  • 4,657
  • 3
  • 32
  • 50
Claudio
  • 884
  • 1
  • 15
  • 31

2 Answers2

8

Try

MessageBox.Show(a + "was your answer");

or

MessageBox.Show(string.Format("{0} was your answer", a));

Using

string.Format()

can be neater for multiple string variables and easier to change the string literal if you need to. See this SO question for a discussion on its use.

Your

MessageBox.Show(a, "was your answer");

throws the text to the title because the method signature of MessageBox.Show() that takes two arguments is for:

public static DialogResult Show(
    string text,
    string caption
)

Displays a message box with specified text and caption.

MSDN

Community
  • 1
  • 1
Sam Leach
  • 12,746
  • 9
  • 45
  • 73
3

You need concatenation

MessageBox.Show(a + "was your answer");
  • Well that was simple. – Claudio Mar 13 '14 at 08:30
  • 1
    @Claudio Yes. Also see the 2nd method in [this answer](http://stackoverflow.com/questions/22372927/c-sharp-multiple-strings-on-the-same-line-in-messagebox/22372937#22372937). –  Mar 13 '14 at 08:31