beaucrawford.net

Give me data or give me death

About the author

Author Name is someone.
E-mail me Send mail

Recent comments

Don't show

Authors

Tags

Don't show

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2010

    Calling TryParse Dynamically

    Most of the common types have a “TryParse” method available.  Here’s a method you can use to dynamically call the corresponding TryParse method for a specific Type:

    public static T ConvertValue<T>(string stringValue)
    {
        if (typeof(T) == typeof(string))
            return (T)Convert.ChangeType(stringValue, typeof(T));
    
        var type = typeof(T);
    
        bool nullableType = type.IsGenericType 
            && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
    
        if (nullableType)
        {
            if (stringValue == null)
                return default(T);
    
            type = new NullableConverter(type).UnderlyingType;
        }
    
        Type[] argTypes = { typeof(string), type.MakeByRefType() };
    
        var tryParse = type.GetMethod("TryParse", argTypes);
    
        if (tryParse == null)
        {
            string exceptionMessage = string.Format("A method named 'TryParse' does not exist for the '{0}' Type.", type.FullName);
            throw new InvalidOperationException(exceptionMessage);
        }
    
        object[] args = { stringValue, null };
    
        bool successfulParse = (bool)tryParse.Invoke(null, args);
    
        if (!successfulParse)
            throw new InvalidCastException();
    
        return (T)args[1];
    }



    I’m currently using this in a code generation scenario where I have a string value and “T” is known at generation time.  Enjoy.


    Categories: C# | Reflection | Code Generation
    Posted by Beau on Tuesday, March 24, 2009 7:35 PM
    Permalink | Comments (3) | Post RSSRSS comment feed

    Comments

    Justin Chase us

    Tuesday, March 24, 2009 9:16 PM

    You could also just do:

    public static T ConvertValue<T>(string value)
    {
    return (T)Convert.ChangeType(value, typeof(T));
    }

    Beau us

    Tuesday, March 24, 2009 10:01 PM

    Good point -- That will work for common types but not things like IPAddress and other types that implement a "TryParse" method by convention.

    Justin Chase us

    Wednesday, March 25, 2009 8:08 AM

    I suppose it also doesn't "try", failure will most likely end up throwing an exception. Hopefully this will be a lot simpler code with the dynamic keyword in C# 4.