Search code examples
c#.nettypeofgettypegeneric-type-argument

Check object is equal to generic type


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?


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