Request.Browser.Version may not be a double
Avoid writing code like this to do browser detection:
if(Double.Parse(Request.Browser.Version) < 5.2) { // 5 or less
Why might this be a problem? Well, Request.Browser.Version is typed in the Base Class Library as a string. It's a string for a reason - because it may not necessarily be a double. When one writes Double.Parse(someString) they're basically saying that the folks who chose the type for Request.Browser.Version were mistaken, and that a double would have been a better chose.
This can be a problem when a browser like IE7.0 beta comes out and the value of Request.Browser.Version is "7.0b." This also applies to Mac's Safari and its User agent version which changed recently from 2.0 to 2.0.1 or 2.0.2.
Exception: Input string was not in a correct format.
Exception: System.FormatException
Message: Input string was not in a correct format.
Source: mscorlib
at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info)
at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider)
at System.Double.Parse(String s)
Unexpected exceptions tend to cramp one's style. I like the philosophy that "if you ever get an unexpected exception, you didn't test your code well enough." Why? Because clearly it wasn't anticipated, otherwise there'd have been code to handle it. This line (and the code around it you can't see) never expected a non-double to be in Request.Browser.Version, but the property's string type was the first tip that other things could happen.
About Scott
Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.
About Newsletter
That doesn't sound right. Perhaps I mean, "when other objects might appear to be more appropriate".
Instead I mean, "if it's a string, realize that it may well not be a double."
System.Version v = new System.Version("7.0b"); //<-- exception here
Console.WriteLine(v.ToString());
On your hosting server you may be pretty safe, but if you plan on distributing the code...
Comments are closed.
Prime example: Selects such as drop downs and list boxes. In WinForm development, the value of a ListItem is an object, whereas in ASP.NET it is a string, so you end up doing a lot of Parse calls to get integer values.