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

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...

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.


Need Your Help

Disabling ng-autocomplete (or disabling a div property in general)

javascript html angularjs autocomplete

I have 2 buttons which select for 2 different cases I want to address. When I select button #2 I want to disable the autocomplete feature on my input bar (which is enabled using ng-autocomplete) b...