2

When should I use XmlConvert.ToString to convert a given value versus the ToString method on the given type.

For example :

int inputVal = 1023;

I can convert this inputVal to string representation using either method:

string strVal = inputVal.ToString();

or

string strVal = XmlConvert.ToString(inputVal);

What is the rule for using XmlConvert.ToString versus doing plain Object.ToString.

João Angelo
  • 56,552
  • 12
  • 145
  • 147
Venki
  • 2,129
  • 6
  • 32
  • 54

1 Answers1

3

The XmlConvert.ToString methods are locale independent so the string representation will be consistent across different locales. With Object.ToString you may get a different representation according to the current culture associated with the thread.

So using one versus the other is a matter of the scenario, XmlConvert lends well if you're exchanging data with another system and want a consistent textual representation for example a double value.

You can see the differences in the following example:

double d = 1.5;

Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-PT");
Console.WriteLine(d.ToString());            // 1,5
Console.WriteLine(XmlConvert.ToString(d));  // 1.5

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

Console.WriteLine(d.ToString());            // 1.5
Console.WriteLine(XmlConvert.ToString(d));  // 1.5
Bart
  • 19,692
  • 7
  • 68
  • 77
João Angelo
  • 56,552
  • 12
  • 145
  • 147