Cast generic type parameter to a specific type in C#
<p>If you need to cast a generic type parameter to a specific type, we can cast it to a object and do the casting like below:</p>
<pre><code>void SomeMethod(T t)
{
    SomeClass obj2 = (SomeClass)(object)t;
}
</code></pre>
<p>Is there a better way to achieve this, rather than casting it to an object and then to a specific type?</p>
<p>Problem:</p>
<p>I have a generic function which accepts a generic type parameter, inside the function based on a type checking I do some operations like below:</p>
<pre><code>    void SomeMethod(T t)
    {
        if (typeof(T).Equals(typeof(TypeA)))
        {
            TypeA = (TypeA)(object)t;
            //Do some operation
        }
        else if (typeof(T).Equals(typeof(TypeB)))
        {
            TypeB = (TypeB)(object)t;
            //Do some operation
        }
    }
</code></pre>