Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable.ToString() vs. Convert.ToString(variable)

Tags:

c#

.net

Let's say I have an integer that I need to convert to a string (I might be displaying the value to the user by means of a TextBox, for example.

Should I prefer .ToString() or Convert.ToString(). They both do the same thing (don't they?).

int someValue = 4;

// You can do this
txtSomeValue.Text = someValue.ToString();

// Or this...
txtSomeValue.Text = Convert.ToString(someValue);

Assuming that there is no runtime difference between the two, then my reasons come down to aesthetics and consistency. Recently I have been favouring Convert.ToString() as to me it says "hey, I want the value of this thing as a string". However I know that this is not strictly true...

like image 623
Richard Ev Avatar asked Nov 28 '08 15:11

Richard Ev


People also ask

What is the difference between convert ToString and ToString () method?

Convert. ToString() has an overload that allows to use CultureInfo, while . ToString() doesn't have such overload.

How do I convert ToString?

ToString(Int32, IFormatProvider) Converts the value of the specified 32-bit signed integer to its equivalent string representation, using the specified culture-specific formatting information.

Why do we use ToString in C#?

ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.


2 Answers

One test is

//This will set the variable test to null:
string test = Convert.ToString(ConfigurationSettings.AppSettings["Missing.Value"]);

//This will throw an exception:
string test = ConfigurationSettings.AppSettings["Missing.Value"].ToString();

Got the above ready example from http://weblogs.asp.net/jgalloway/archive/2003/11/06/36308.aspx

You can find some benchmarks between the two at http://blogs.msdn.com/brada/archive/2005/03/10/392332.aspx

So, it depends what you prefer and what your style is.

like image 63
rajesh pillai Avatar answered Nov 02 '22 23:11

rajesh pillai


With its large number of overloads, Convert.ToString() is useful as a catch-all for all sorts of input types, handy when you are dealing with a potential range of types. If you know that your input is definitely an "int", I would use the ToString() method on it directly (that's what Convert.ToString() is going to be calling by proxy anyways.)

like image 44
James Orr Avatar answered Nov 02 '22 22:11

James Orr