Showing posts with label Reflection. Show all posts
Showing posts with label Reflection. Show all posts
Sunday, 3 March 2013

Converting a string to the 'best-fitting' type

I answered a pretty interesting question on Stack Overflow yesterday, creating a method that takes a string and returns the value converted to the 'best-fitting' type out of a set of types boxed in dynamic. Here is the full question:

I have been playing around with converting a string to a value type in .NET, where the resulting value type is unknown. The problem I have encountered in my code is that I need a method which accepts a string, and uses a "best fit" approach to populate the resulting value type. Should the mechanism not find a suitable match, the string is returned.

This is what I have come up with:

public static dynamic ConvertToType(string value)
{
    Type[] types = new Type[]
    {
        typeof(System.SByte),
        typeof(System.Byte),
        typeof(System.Int16),
        typeof(System.UInt16),
        typeof(System.Int32),
        typeof(System.UInt32),
        typeof(System.Int64),
        typeof(System.UInt64),
        typeof(System.Single),
        typeof(System.Double),
        typeof(System.Decimal),
        typeof(System.DateTime),
        typeof(System.Guid)
    };
    foreach (Type type in types)
    {
         try
         {
               return Convert.ChangeType(value, type);
         }
         catch (Exception)
         {
             continue;
         }
    }
    return value;
}

I feel that this approach is probably not best practice because it can only match against the predefined types.

Usually I have found that .NET accommodates this functionality in a better way than my implementation, so my question is: are there any better approaches to this problem and/or is this functionality implemented better in .NET?

Intelligent type conversion in .NET, series0ne