Working for PrimativeType.TryParse
I'm used to using TryParse to try and 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 anyone knows a better way to do this other than using the ternary operator.
Decision
Hello again,
Since the post is closed I'm sure this solution will be buried there, but I created a cool class that solves the problem above using the advice I was given. Just wanted to put the code in there in case someone stumbled 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 easy to use. Just pass in the type you expect as generic and provide the string value to be parsed and a default value if no string is parsed. If you provide a class instead of a primitive type it willthrow new ArgumentException("Generic type must be a valid Value Type that has a Parse method.");
source to share
Insert it into a function.
Function BooleanOrDefault(byval value as string) as Boolean
dim isBoolean as Boolean, boolValue as Boolean
dim defaultValue as Boolean = False
isBoolean = Boolean.TryParse(value, out boolValue)
BooleanOrDefault = IIF(isBoolean, boolValue, defaultValue)
End Function
source to share
- Insert a comment.
- Bring up the juniors, they won't get better if they don't ask and you answer their questions.
- Both of the above.
You can create a function that makes the whole step much more explicit (it might be easier on scrolls too) and use that instead of your separate line. code.
source to share