Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not write MessageBox.Show("asdfasdf{0}", i);?

Tags:

c#

windows

int i = 85; 
Console.WriteLine("My intelligence quotient is {0}", i);  // Kosher
MessageBox.Show("My intelligence quotient is {0}", i); // Not Kosher

I find this most distressful an debilitating. One works and not the other? What is the source of this behavioural incongruity? The more I think about it the less I can imagine, and failure to understand too often turns to self-loathing.

like image 477
Epic Nobody Avatar asked Nov 10 '11 08:11

Epic Nobody


3 Answers

The Show() method simply has no proper overload.

It was added to Console.WriteLine as matter of convenience, but it's not integral part of every .NET method.

To achieve same effect, use string.Format manually:

MessageBox.Show(string.Format("asdfasdf{0}", i)); // Kosher
like image 87
Shadow Wizard Hates Omicron Avatar answered Oct 18 '22 11:10

Shadow Wizard Hates Omicron


Console.Writeline has these overloads:

  • http://msdn.microsoft.com/en-us/library/system.console.writeline.aspx

In particular, an overload that accepts a format string and a params array.

Here's another method that is quite similar:

  • http://msdn.microsoft.com/en-us/library/system.string.format.aspx

I don't know why MessageBox.Show doesn't have the overload. I'd guess it is because there are already so many other overloads for that method.

But you can get a similar effect by adding string.Format to it:

public void ShowMessageBox(string format, params object[] args)
{
    MessageBox.Show(string.Format(format, args));
}

// ...

ShowMessageBox("You entered: {0}", someValue);
like image 21
Merlyn Morgan-Graham Avatar answered Oct 18 '22 11:10

Merlyn Morgan-Graham


Why is hard to tell (it is just how MS defined it) but IF you want to write "congruent" code for both cases then you can use string.Format - for example like this:

MessageBox.Show (string.Format ("asdfasdf{0}", i));

or

Console.WriteLine (string.Format ("asdfasdf{0}", i)); // although this is unneccesary!
like image 45
Yahia Avatar answered Oct 18 '22 12:10

Yahia