Hello All,
I have become accustomed to using TryParse for attempting to parse unknown types:
Dim b As Boolean
Dim qVal As Boolean = If(Boolean.TryParse(Request.QueryString("q").Trim(), b), b, False)
or
bool b;
bool qVal = (Boolean.TryParse(Request.QueryString("q").Trim(), out b) ? b : false;
So, just curious if someone knows a better way of doing this other than using a ternary operator.
Solution
Hello Again,
Since the post has been closed, I'm sure this solution will get buried out there, but I created a pretty cool class that solves the problem above using the advice I was given. Just wanted to put the code out there in case some one stumbles upon this thread and would like to use it:
public static class PrimitiveType
{
/// <summary>
/// This function will return a parsed value of the generic type specified.
/// </summary>
/// <typeparam name="valueType">Type you are expecting to be returned</typeparam>
/// <param name="value">String value to be parsed</param>
/// <param name="defaultValue">Default value in case the value is not parsable</param>
/// <returns></returns>
public static valueType ParseValueType<valueType>(string value, valueType defaultValue)
{
MethodInfo meth = typeof(valueType).GetMethod("Parse", new Type[] { typeof(string) });
if (meth != null)
{
try
{
return (valueType) meth.Invoke(null, new object[] { value });
}
catch (TargetInvocationException ex)
{
if (ex.InnerException.GetType() == typeof(FormatException) || ex.InnerException.GetType() == typeof(OverflowException))
{
return defaultValue;
}
else throw ex.InnerException;
}
}
else
{
throw new ArgumentException("Generic type must be a valid Value Type that has a Parse method.");
}
}
}
It's pretty simple to use. Just pass in the type you're expecting as the generic and provide a string value to be parsed and a default value in case the string is not parsable. If you provide a class instead of a primitive type it will throw new ArgumentException("Generic type must be a valid Value Type that has a Parse method.");