Question

I have a method that does some type conversion. I don't want to go through the whole process if the type is equal to the generic types passed. Here's a snippet.

    public static T ConvertTo<T>(this object @this)
    {
        if (typeof(T) == @this.GetType())
            return (T)@this;
    }

I'm checking is the object @this is already of type T which seems to work, but is this the best way of doing this?

Était-ce utile?

La solution

You can use IsInstaceOfType method and is to check the type.

public static T ConvertTo<T>(this object @this)
{
    if (@this is T)
       return (T)@this;
    else
       return default(T);
}

Autres conseils

This might also work

public static T ConvertTo<T>(this object @this)
{
    return (T)System.Convert.ChangeType(@this, typeof(T));
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top