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,
void SomeMethod(T t)
{
SomeClas
A better design is to put a constraint on it that is common between type T and the class you want to expect in your method, in this case SomeClass.
class SomeConsumer where T : ISomeClass
{
void SomeMethod(T t)
{
ISomeClass obj2 = (ISomeClass) t;
}
}
interface ISomeClass{}
class SomeClass : ISomeClass {}
That is bad design. Try to move that "operation" into the class itself so the caller does not have to know the type. If that is not possible share more of what is being done, what you want to accomplish though is that you do not have a stack of if/else statements where execution depends on the type of object being passed in to the method.
class SomeConsumer where T : ISomeClass
{
void SomeMethod(T t)
{
ISomeClass obj2 = (ISomeClass) t;
// execute
t.Operation();
}
}
interface ISomeClass{
void Operation();
}
class SomeClass : ISomeClass {
public void Operation(){/*execute operation*/}
}