Getting Best of Generics for Type Conversion


Not a long time ago I worked hard with reflection and type conversion and decided to save the time getting some C# snippets for doing the type conversion. I don’t like the standard System.Convert to be honest so I was looking for some generics implementation. Imagine my surprise when Googling gave me nothing interesting towards my request. This is rather common stuff I guess and there was so much talking about generics that I would better think that Google was buggy that day πŸ˜‰

I managed to find only one sample that was almost close to what I wanted. I won’t give the sources but in two words: the guy implemented a generic method that was getting a type. Inside he did the switch case or multiple if-else clauses to check it’s generic attributes and give the appropriate result. Good beginning and so stupid end πŸ™‚

I’ve placed my approach to the couple of forums some months before I started to fill my space, and to be honest I didn’t check today whether any good solutions appeared, but I strongly want to put it here…

So meet the raw generics wrapper for System.Convert. I think this is the smallest implementation possible in this case.

public static class Converter
{
    public static T Convert<T>(object value) where T : IConvertible
    {
        return (T)System.Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
    }

    public static T Convert<T, K>(K value)
        where T : IConvertible
        where K : IConvertible
    {
        return (T)System.Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
    }
}

No multiple ifs and no switches πŸ™‚

Hope it will save someone’s time one day…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s