Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Work Around For PrimativeType.TryParse

Tags:

c#

parsing

vb.net

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

like image 734
regex Avatar asked Mar 14 '26 04:03

regex


1 Answers

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");
like image 138
Neil Barnwell Avatar answered Mar 15 '26 16:03

Neil Barnwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!