I'm attempting to integrate several comparable techniques into a single generic method. I have a few methods that return the value of a querystring, or null if the querystring doesn't exist or isn't formatted properly. This would be simple if all of the types were natively nullable, however for numbers and dates, I have to use the nullable generic type.
Here's what I've got right now. However, if a numeric number is invalid, it will return a 0, which is regrettably an acceptable value in my cases. Is there anyone who can assist me?
public static T GetQueryString<T>(string key) where T : IConvertible
T result = default(T);
if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
string value = HttpContext.Current.Request.QueryString[key];
result = (T)Convert.ChangeType(value, typeof(T));
//Could not convert. Pass back default value...
result = default(T);