C# Generic Type Conversion

by UnquaLe 24. October 2007 19:45

I thought C# Generics are useful also for type convertion. I messed code alittle and the emergent code snippet looks fine for me. It is easy and simple. 

public class GenericConverter
{
    public static T Parse<T>(string sourceValue) where T : IConvertible
    {
      return (T)Convert.ChangeType(sourceValue, typeof(T));
    }

    public static T Parse<T>(string sourceValue, IFormatProvider provider) where T : IConvertible
    {
      return (T)Convert.ChangeType(sourceValue, typeof(T), provider);
    }
}

//Usage
DateTime datetime = GenericConverter.Parse<DateTime>("12.10.2007");


IFormatProvider providerEN = new System.Globalization.CultureInfo("en-US", true);
IFormatProvider providerTR = new System.Globalization.CultureInfo("tr-TR", true);

DateTime x = GenericConverter.Parse<DateTime>("12.10.2007", providerTR); // ddMMyyyy
DateTime y = GenericConverter.Parse<DateTime>("12.10.2007", providerEN); // MMddyyyy

int iValue = GenericConverter.Parse<int>("12");


Enjoy !.

Doga. 

Tags:

Development

Comments

10/25/2007 1:22:09 AM #

trackback

Trackback from DotNetKicks.com

C# Generic Type Conversion

DotNetKicks.com | Reply

10/25/2007 12:11:56 PM #

Gokhan Demir

Hey man, this was a great idea! Nicely done!

Gokhan Demir Turkey | Reply

10/25/2007 5:06:26 PM #

Garry Shutler

I don't understand the point of this. How is this better than DateTime.Parse, Integer.Parse or creating a static method on whatever class you wish to convert to?

Garry Shutler United Kingdom | Reply

2/17/2008 11:20:55 PM #

Tuna Toksoz

Nullable Type Conversion


  public static class TConverter
  {
    public static T ChangeType<T>(object value)
    {
      return (T)ChangeType(typeof(T),value);
    }
    public static object ChangeType(Type t,object value)
    {
      TypeConverter tc = TypeDescriptor.GetConverter(t);
      return tc.ConvertFrom(value);
    }
    public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
    {

      TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));

    }

  }


this seems to be a better solution. Also works for nullables.

Tuna Toksoz Turkey | Reply

5/2/2008 6:20:32 AM #

Michael

The live preview doesn't work:
-----------------------------

Here's my version that also works with nullable types:

public static T Parse<T>(object value)
{
    try
    {
        Type type = typeof(T);

        if (type.Name == "Nullable`1")
            type = Nullable.GetUnderlyingType(type);

        if (type.BaseType.Name == "Enum")
            return (T)Enum.Parse(type, value.ToString().Replace(" ", ""));

        if (type.Name == "Guid")
            return (T)(object)(new Guid(value.ToString()));

        return (T)Convert.ChangeType(value, type);
        }
    catch (Exception) { return default(T); }
}

Michael New Zealand | Reply

5/2/2008 6:23:17 AM #

Michael

Ok try with version 3:
----------------------

Here's my version that also works with nullable types:

public static T Parse<T>(object value)
{
    try
    {
        Type type = typeof(T);

        if (type.Name == "Nullable`1" )
            type = Nullable.GetUnderlyingType(type);

        if (type.BaseType.Name == "Enum" )
            return (T)Enum.Parse(type, value.ToString().Replace(" ", "" ));

        if (type.Name == "Guid" )
            return (T)(object)(new Guid(value.ToString()));

        return (T)Convert.ChangeType(value, type);
        }
    catch (Exception) { return default(T); }
}

Michael New Zealand | Reply

5/2/2008 6:53:26 AM #

Michael

Actually Tuna's solution is a lot simpler and works with Enum and Guid as well. Although how does RegisterTypeConverter work and are there any examples where you would need it? A small addition that I had in mine is to return the default value in case the input is invalid.

public static T Parse<T>(object value)
{
    try { return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value); }
    catch (Exception) { return default(T); }
}

It's easier to test for invalid input by testing to see if the function returns a default value then handling the exception. It also allows you to define a default like:

int val = Parse<int?>(Request["switch"]) ?? 2

Michael New Zealand | Reply

4/9/2009 6:45:44 PM #

Manitra

Hi,

Thanks for this tips Smile

Garry Shutler, this kind of method is usefull in automatic conversion scenario like :
- injecting QueryString params into strongly typed properties of your pages/webcontrols
- injecting Configuration informations into strongly type properties of your DAOs
- doing some manual, strongly typed, databinding

Manitra France | Reply

2/16/2010 11:42:40 AM #

trackback

Using extension methods to handle Xml

Using extension methods to handle Xml

The #Crypt | Reply

2/23/2010 1:54:56 PM #

Aluminium bi fold doors

Good code source, thanks alot for sharing, hope it will help me out on my work. thanks again.

Aluminium bi fold doors United Kingdom | Reply

3/1/2010 2:05:06 AM #

Fatcow Review

Should I get a Dedicated Hosting? At the moment I am using lunarpages but they keep turning off my websites due to high server overload. Im getting about 3,000 unique views a day. What brand should I get?

Fatcow Review United States | Reply

3/3/2010 9:59:31 AM #

wow mobiles

WoW Mobiles is awesome! I get free mobile service with t-mobile because I refered 3 people to wow. You can too!

wow mobiles United States | Reply

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen