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

后端 未结 2 920
不思量自难忘°
不思量自难忘° 2020-12-06 17:15

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

相关标签:
2条回答
  • 2020-12-06 17:40

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

    0 讨论(0)
  • 2020-12-06 18:03

    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.

    0 讨论(0)
提交回复
热议问题