Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a universal type conversion method

Tags:

c#

.net

What I want to do is:

bool Convert( out Object output, Object source)
{
   // find type of output.
   // convert source to that type if possible
   // store result in output.

   return success
} 

Is it possible?

Obviously, there is a brute force massive "if" construct that could work, but that would require writing an if block for every conceivable data type. Even assuming we'll limit it to primitives and strings, it's still a huge chunk of code. I'm thinking about something a bit more reflective.

Aside: While going through the api, I came across the Convert.IsDBNull() method, which will save me a lot of

 if ( !databasefield.GetType().Equals( DBNull.Value ) )

Why in the name of G-d is it in Convert? Why not DBNull.IsDBNull() ?

like image 896
Chris Cudmore Avatar asked Feb 05 '26 09:02

Chris Cudmore


1 Answers

Here is a sample that I use, you can inject other complex conversions into it by registering other type converters.

public static class Converter
{
    public static T Convert<T>(object obj, T defaultValue)
    {
        if (obj != null)
        {
            if (obj is T)
            {
                return (T)obj;
            }

            TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));

            if (converter.CanConvertFrom(obj.GetType()))
            {
                return (T)converter.ConvertFrom(obj);
            }
        }

        return defaultValue;
    }
like image 74
Brian Rudolph Avatar answered Feb 07 '26 22:02

Brian Rudolph