views:

221

answers:

2

Is there any difference between Convert.ToString Method and Object.ToString() in C#.net other than how these handle null value. There could be some difference between the two in Globalization Perspective.

A: 

Contert.ToString for the most part calls ToString on the value that is passed in. There are only a few exception for example

Convert.ToString(object, IFormatProvider) which checks if the value implements IConvertable and delegates to that otherwise if the value is not null delegates to value.ToString.

Convert.ToString(IntXX, Int32) where XX is 16, 32, 64. This does a base conversion.

So I do not believe that there is any difference interms of globalization between the two.

Chris Taylor
Thank you Taylor for that valuable piece of Information.But I still have doubt when we check the number of overloads that these two supports. Imagine,double d = 1000;d.Tostring() has 4 overloads.ie it can take the IformatProvider as well as Format String as parameters.But when we come to Convert.ToString(d,XYZ) , there is no way we can spceify the Format String. Only IformatProvider .So what could that mean ??
Ananth
@Ananth, the Format String does not impact the localization of the string. So for example, d.ToString("F2", new CultureInfo("en-GB")) will return the string 1000.00, while d.ToString("F2", new CultureInfo("el-GR")) will return 1000,00 (Notice the ',' as decimal point). So in this case the format string did not change, and does not impact the localization of the string only the format.
Chris Taylor
A: 

Yes and no.

For example, the Convert.ToString(int) method, is identical to the Int32.ToString() method, as MSDN states in the 'Remarks' section: "This implementation is identical to Int32.ToString()." However, the Convert class also offers overrides which take an IFormatProvider as a second parameter (e.g. Convert.ToString(int, IFormatProvider)), and this can be used to adjust the output format, e.g. by passing a CultureInfo instance.

gehho
Of course this is still just calling value.ToString and passing the IFormatProvider directly. So Convert.ToString is offering the same support as ToString directly on the object, except for the few cases I mentioned in my response.
Chris Taylor
Well, that is true, but Ananth was asking for differences compared to `Object.ToString()` (which `Int32.ToString()` overrides), and this method does not provide an `IFormatProvider` parameter.
gehho
Thank You gehho. With "Object.ToString()", i meant types like Int32,Double etc.. x.toString() gives more overloads(including IFormatProvider) than what convert.ToString() gives...
Ananth