20 December 2010

Convert objects to string and back without culture problems

After storing various values as strings in a database, I had some troubles with parsing these values back to their original types (doubles, datetimes, etc.) on various clients.
As it seems, the most commonly used ways (such as ToString(), Convert.ToString(), Convert.ToDecimal() and DateTime.Parse()) perform these conversions based on the current culture. This means that the whole format of a datetime can differ on different clients, but also the thousands separator in numbers and also their decimal mark as all of these are culture dependent.

The best way I have found to convert values to strings and back, independent of the current culture, is with the use of the FormatterConverter class. This class converts objects to other objects, independent of any culture (probably using the InvariantCulture).

It can be used as follows:

FormatterConverter fConverter = new FormatterConverter();
double d = fConverter.ToDouble(stringValue);
string s = fConverter.ToString(datetimeValue);

It can be used for other types, by using its following method:
object Convert(object obj, Type t)

For instance, to convert a string to a Car object, you can use the following:
Car myCar = fConverter.Convert(stringValue, typeof(Car)) as Car;
you have to cast the result to Car, as the Convert method returns an object.

No comments :