Avoid System.Windows.Rect.ToString()

System.Windows.Rect.ToString() is documented as returning a string in “the following form: “X,Y,Width,Height””.

It seems like this method is the complement to the Parse method, which accepts the “string representation of the rectangle, in the form “x, y, width, height””.

Unfortunately, while Parse is culture-invariant (as documented), ToString follows the .NET convention of returning locale-sensitive results; you need to call the ToString(IFormatProvider) overload to produce a string in the “x,y,width,height” format (that can be accepted by Parse).

Rect rect = new Rect(1.5, 2, 3.5, 4);
string s;

s = rect.ToString(); // "1.5,2,3.5,4"
Rect.Parse(s); // success

Thread.CurrentThread.CurrentCulture = new CultureInfo("de"); // or "es", "fr", etc.

s = rect.ToString(); // "1,5;2;3,5;4"
Rect.Parse(s); // throws FormatException

s = rect.ToString(CultureInfo.InvariantCulture);
Rect.Parse(s); // success

I filed a bug report, even though this is arguably an error in the documentation, not in the .NET Framework itself.

Posted by Bradley Grainger on January 02, 2012