Josbel Luna
Josbel Luna

Reputation: 2824

Is there a way to get the Generic Type from an Extension method?

Consider this method:

public static TResult CastTo<T, TResult>(this T arg)
        {
            TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(T));
            bool? converter = typeConverter?.CanConvertTo(typeof(TResult));
            if (converter != null && converter == true)
                return (TResult)typeConverter.ConvertTo(arg, typeof(TResult));
            else
                return default(TResult);
        }

Is there a way to set the generic type from the extension method, I mean, Instead to call:

 string s = "1";
 s.CastTo<string, int>();

Something to get the input type directly from the class who's calling. I'm pretty new with C# and I want to know this issue.

Upvotes: 1

Views: 80

Answers (2)

Arthur Rey
Arthur Rey

Reputation: 3058

You can ommit the type when your generic method returns nothing:

public static void CastTo<T, TResult>(this T arg, out TResult var)
{
    TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(T));
    bool? converter = typeConverter?.CanConvertTo(typeof(TResult));
    if (converter != null && converter == true)
        var = (TResult)typeConverter.ConvertTo(arg, typeof(TResult));
    else
        var = default(TResult);
}

And you use it like so:

string s = "1";
int i;
s.CastTo(out i);

It will know both the base type and output type without having to explicitely name them.

Upvotes: 3

Backs
Backs

Reputation: 24903

Use object type:

    public static TResult CastTo<TResult>(this object arg)
    {
        TypeConverter typeConverter = TypeDescriptor.GetConverter(arg.GetType());
        bool? converter = typeConverter.CanConvertTo(typeof(TResult));
        if (converter != null && converter == true)
            return (TResult)typeConverter.ConvertTo(arg, typeof(TResult));
        else
            return default(TResult);
    }

Upvotes: 2

Related Questions