Converting number to String - Different Approaches

  • Thread starter Thread starter mac
  • Start date Start date
M

mac

Assume you have a textbox named "displayValue"

What is the difference (if any) between these two approaches:

1.)
float var;
var = 0.42F;
displayValue.Text = var.ToString

2.)
float var;
var = 0.42F;
displayValue.Text = Convert.ToString(var);


Is one way generally preferred over the other?


Thanks,

Mac
 
These both type casts are almost identical.

Convert.ToString just call your value.ToString(CultureInfo.CurrentCulture);
For some types it miss CultureInfo.CurrentCulture

--
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
mac said:
Assume you have a textbox named "displayValue"

What is the difference (if any) between these two approaches:

1.)
float var;
var = 0.42F;
displayValue.Text = var.ToString

ToString() can accept IFormatProvider and a string format, making it
more flexible. If you have a custom value type and it overrides
ToString(), then calling it directly on the instance won't cause boxing.
2.)
float var;
var = 0.42F;
displayValue.Text = Convert.ToString(var);

This will call var.ToString, and may cause boxing if your value type is
not special-cased by Convert (float is, of course).
Is one way generally preferred over the other?

I personally never use the Convert class except for Base64 conversions.
For most "display value" kind of conversions, I typically use
string.Format().

-- Barry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top