There seems to be a lot of confusion around converting strings (usually) to their appropriate datatype, whilst validating it on the fly as well. Wherever I look - blogs, articles, code samples, forums.. a few people seem to have a preferred way of dealing with these scenarios.
The case is usually a string/object that comes from an unknown source, such as QueryString, Session/Viewstate, WebService, and so on...
I've seen many different examples:
Say we're trying to get the id=
Query String and use it in our code as an integer. But someone tampered with our URL and changed it to
One way
int id = Convert.ToInt32(Request["id"]);
// "Input string was not in a correct format"
Another way
int id = (int)Request["id"];
// "Input string was not in a correct format"
Yet another way
int id = int.Parse(Request["id"]);
// "Input string was not in a correct format"
I have ever seen this (And it kind of makes sense to throw an exception and notify the user)
int id = 0;
try {
id = Convert.ToInt32(Request["id"]);
}
catch(Exception ex) {
lblError.Text = ex.Message;
}
if(id > 0) { ... }
Lastly, and the one I personally use
int id = 0;
int.TryParse(Request["id"], out id);
// make sure it's not 0
if(id > 0) { // live a happy life }
This goes for all the other types, bool
, double
, decimal
and so on..
Please help me understand what the correct way is, as I find myself using this on a day-to-day basis.