ZuluAlphaCharlie
ZuluAlphaCharlie

Reputation: 287

Generic Method Return Type as Type parameter

I have an extension method that is working ok to cast string values into various types, which looks something like this:

public static T ToType<T> (this string value, T property)
    {
        object parsedValue = default(T);
        Type type = property.GetType();

        try
        {
            parsedValue = Convert.ChangeType(value, type);
        }
        catch (ArgumentException e)
        {
            parsedValue = null;
        }

        return (T)parsedValue;
    }

I'm unhappy about the way this looks when calling the method, however:

myObject.someProperty = stringData.ToType(myObject.someProperty);

Specifying the property just to obtain the property's type seems redundant. I would rather use a signature like this:

public static T ToType<T> (this string value, Type type) { ... }

and have T end up to be the Type of type. This would make calls much cleaner:

myObject.someProperty = stringData.ToType(typeof(decimal));

When I try to call this way, however, the editor complains that the return type of the extension method can't be infered from usage. Can I link T to the Type argument?

What am I missing?

Thanks

Upvotes: 11

Views: 32749

Answers (3)

Sayse
Sayse

Reputation: 43330

Is this what you are looking for? I've added an extra catch for cases where the cast isn't valid also

Decimal i = stringName.ToType<Decimal>();

public static T ToType<T>(this string value)
{
     object parsedValue = default(T);
     try
     {
         parsedValue = Convert.ChangeType(value, typeof(T));
     }
     catch (InvalidCastException)
     {
         parsedValue = null;
     }
     catch (ArgumentException)
     {
         parsedValue = null;
     }
     return (T)parsedValue;
} 

Edit

a shortcut approach to fix Anton's comment

if (typeof(T).IsValueType)
   return default(T);

Upvotes: 17

joe
joe

Reputation: 8654

I'm using this for a generic conversion:

    public bool ConvertTo<T>(object from, out T to) {
        to = default(T);
        if (from is T) { to = (T)from; return true; }                                           
        Type t = typeof(T);
        //TypeConverter converter = p.converter == null ? TypeDescriptor.GetConverter(t) : p.converter;
        TypeConverter converter = TypeDescriptor.GetConverter(t);
        if ((converter != null) && (converter.CanConvertTo(t))) {
            try { to = (T)converter.ConvertTo(null, culture, from, t); return true; }
            catch { }
        }
        try { to = (T)Convert.ChangeType(from, t, culture); return true; }
        catch { }
        return false;                                                                                       
    }

    public bool ConvertTo(object from, out object to, Type type) {
        to = null;
        if (from.GetType() == type) { to = from; return true; }     
        TypeConverter converter = TypeDescriptor.GetConverter(type);
        if ((converter != null) && (converter.CanConvertTo(type))) {
            try { to = converter.ConvertTo(null, culture, from, type); return true; }
            catch { }
        }
        try { to = Convert.ChangeType(from, type, culture); return true; }
        catch { }
        return false;                                           
    }

Before calling Convert.ChangeType, this checks if there is a TypeConverter for the given variable.

Call it this way:

int i = 123;
string s;
if (ConvertTo<string>(i, out s) {
    // use s
}

Upvotes: 0

McAden
McAden

Reputation: 13970

Why use property at all? Just change how you're setting your type variable to the type of your generic.

    public static T ToType<T>(this string value)
    {
        object parsedValue = default(T);
        Type type = typeof(T);

        try
        {
            parsedValue = Convert.ChangeType(value, type);
        }
        catch (ArgumentException e)
        {
            parsedValue = null;
        }

        return (T) parsedValue;
    }

Usage:

myObject.someProperty = stringData.ToType<decimal>()

Upvotes: 2

Related Questions