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
Stumbled across this, and wanted to provide an updated answer for anyone else who found this later. In newer C# versions (8.0 as I write this), pattern matching will allow you to do this in a far more concise way:
void SomeMethod(T t)
{
switch(t)
{
case TypeA a:
// Do some operation using a.
Console.WriteLine($"{a} is a TypeA!");
break;
case TypeB b:
// Do some operation using b.
Console.WriteLine($"{b} is a TypeB!");
break;
default:
// Handle this case.
Console.WriteLine("I don't know what this type is.");
break;
}
}
This will check the type of the object, and if it finds a match will assign it to the indicated variable in one step, which then becomes availabe to use in the body of that case. (You can also do something similar in if statements: if (t is TypeA a) a.DoSomething(); ...
)
All that being said, I do agree with the other responses that you should either constrain this as much as possible (void SomeMethod
) or move the operation into the classes you're testing, if possible.