If you have been looking for a nice and clean way to parse your query string values, I have come up with this:
/// <summary>
/// Parses the query string and returns a valid value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The query string key.</param>
/// <param name="value">The value.</param>
protected internal T ParseQueryStringValue<T>(string key, string value)
{
if (!string.IsNullOrEmpty(value))
{
//TODO: Map other common QueryString parameters type ...
if (typeof(T) == typeof(string))
{
return (T)Convert.ChangeType(value, typeof(T));
}
if (typeof(T) == typeof(int))
{
int tempValue;
if (!int.TryParse(value, out tempValue))
{
throw new ApplicationException(string.Format("Invalid QueryString parameter {0}. The value " +
"'{1}' is not a valid {2} type.", key, value, "int"));
}
return (T)Convert.ChangeType(tempValue, typeof(T));
}
if (typeof(T) == typeof(DateTime))
{
DateTime tempValue;
if (!DateTime.TryParse(value, out tempValue))
{
throw new ApplicationException(string.Format("Invalid QueryString parameter {0}. The value " +
"'{1}' is not a valid {2} type.", key, value, "DateTime"));
}
return (T)Convert.ChangeType(tempValue, typeof(T));
}
}
return default(T);
}
I have always wanted to have something like that and finally got it right ... at least I think so ...
The code should be self explanatory ...
Any comments or suggestions to make it better are appreciated.