tags:

views:

195

answers:

3

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.");

+1  A: 
  1. Put a comment in.
  2. Educate the juniors, they won't get better unless they ask, and you answer their questions.
  3. Both of the above.

You could create a function that does the entire step in a much more explicit way (it might be easier on the scrolbars too) and use that in place of your single line. of code.

gbjbaanb
+5  A: 

I've previously wrapped querystrings in my own class. Then I can do something like the following:

var qs = new QueryString(Request.QueryString);
bool q = qs.Get<bool>("q");
Neil Barnwell
shahkalpesh
That's a really good approach. Thanks for the advice.
regex
I wish I could give you +1 again. This style reminds me of datareader.GetInt :)
shahkalpesh
I also like to add methods such as GetInt that take a default value if the item doesn't exist in the query string.
KeeperOfTheSoul
Instead of wrapping the NameValueCollection of Request.QueryString you could also make an extension method like this: public static T Get<T>(this NameValueCollection collection, string name) where T : struct { // Implementation... }
JohannesH
+2  A: 

Wrap 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
shahkalpesh