Tech Off Post

Single Post Permalink

View Thread: C# Sting converstion
  • User profile image

    TommyCarlier said:
    Sven Groot said:

    It's a pity that .NET doesn't make a distinction between "data strings" and "display strings". I mean, instead of ToString() you'd have ToDataString() which returns a culture-independent string of data, and ToDisplayString() which returns a culture-dependent string used for display purposes.

    In my own code, I've created some static classes with extension methods to convert values (int, long, DateTime, ...) to data strings and back. You can then write code like this:

    DateTime d = DateTime.Today;
    string s = d.ToDataString(); // s will be "2009-12-29"
    d = s.ToDateTime();

    It also knows about nullable values, so you can use s.ToDateTimeOrNull() or convert nullable DateTime to data string.

    You can find the code on CodePlex (in folder TC/src/TC.Core in the files ConvertXXX.cs).

    Because ToDataString is essentially the same thing as serialisation, and there are dedicated classes for that. I'm happy with the current simplistic design and I don't feel it needs to be refactored any. If a class has a meaningful culture-specific string representation then always use the IFormatProvider overload.