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?

Was it helpful?

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);
}

OTHER TIPS

This might also work

public static T ConvertTo<T>(this object @this)
{
    return (T)System.Convert.ChangeType(@this, typeof(T));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top