9

I have some code like:

int value = 5;
MessageBox.Show ( value );

and the MessageBox.Show complains saying:

"cannot convert from 'int' to 'string'"

I seem to remember some cases where values seem to be implicitly converted to string values, but can't recall them exactly.

What's the reason behind this decision that any value isn't implicitly convertible to string values?

Randy Levy
  • 22,566
  • 4
  • 68
  • 94
Joan Venge
  • 315,713
  • 212
  • 479
  • 689
  • Possible duplicate of http://stackoverflow.com/questions/751303/cannot-implicitly-convert-type-x-to-string-when-and-how-it-decides-that-it – rsenna Apr 01 '11 at 17:08
  • 1
    Is this question about missing implicit conversion, or about calling the Messagebox.Show with an integer? – oɔɯǝɹ Apr 07 '11 at 18:28

4 Answers4

18

MessageBox.Show() only accepts a string. When you use something like Debug.WriteLine, it accepts a bunch of different object types, including object, and then calls ToString() on that object. This is probably what you're experiencing.

Mike Park
  • 10,845
  • 2
  • 34
  • 50
12

A short solution (everywhere you need a string):

 MessageBox.Show(""+value);

But I would prefer a ToString() or a String.Format() in most cases.

To answer the "Why" part: because implicit conversions can be dangerous and can undermine type-safety.
"1" + 2 = "12" = 12, not always what you want or expect.

H H
  • 263,252
  • 30
  • 330
  • 514
  • Good point Henk, I didn't know the cons of implicit conversions. – Joan Venge Apr 01 '11 at 17:13
  • @Joan: If you're familiar with the way javascript handles strings (or at least seen it enough), you will appreciate that most languages don't do as much implicit conversions. :) Look at [this](http://stackoverflow.com/questions/1995113/strangest-language-feature/1995298#1995298) and all the other javascript related answers. – Jeff Mercado Apr 02 '11 at 07:46
3

For the exact reason, you would have to ask either the C# compiler guys, or one of the .NET runtime guys.

However, there are no places in the .NET framework or the C# language where values are automatically and implicitly convertible to strings.

You might, however, think of the way string concatenation works, but that only works because there are a lot of overloads on the string.Concat method, including one that takes an object.

In other words, this is allowed:

string s = "Hello there: " + 4;

Other methods around in the framework also has lots of overloads, such as Debug.WriteLine and such, where it will easily accept your integer or decimal, convert it to a string through a call to .ToString, and then print it.

It isn't, however, something built into string or int, but the method itself.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
-1

Try

MessageBox.Show(value.ToString());
Chuck Savage
  • 11,775
  • 6
  • 49
  • 69