You can't switch on the Type
object, but you can switch on it's name:
switch( typeof(TContract).Name )
{
case "Namespace.SomeTypeName": ...
}
In general, however, this rarely proves to be a good design choice. You are better off passing in a delegate or a object that implements an interface (or even a generic type parameter) to define the "strategies" for handling different types.
This is a common question about designing and writing generic types - namely the ability to perform entirely different actions based on the type of the generic type parameters. I tend to view this as a code smell that you may not be using generics as they were intended and your design is "going against the grain", so to speak.
However, in some cases it is indeed necessary to perform processing that varies by type, in which case passing in a separate type (either to the constructor as another generic parameter) allows you to separate the different concerns into "strategies" that are more extensible, cleaner, and less coupled to the implementation of the generic class. An example might be:
interface IOperation<T>
{
T Add( T first, T second );
}
public class Calculator<T,TOp>
where TOp : IOperation<T>, new()
{
private readonly TOp m_Op = new TOp();
public T Sum( IEnumerable<T> values )
{
T accum = default(T);
foreach( var val in values )
accum = m_Op( accum, val );
return accum;
}
}
Now you can write different implementations of IOperation<T>
that are appropriate to different types (integers, floating point numbers, complex numbers, matrixes, etc). The generic class Calculator<T,TOp>
is then separate from the operations that vary by type, but is free to compose them as it sees fit.
In .NET 4.0 it's possible to use dynamic
to dispatch to overloads of one or more methods that are specialized for certain types. This approach, while simpler, incurs the performance penalty of essentially invoking the compiler at runtime to figure out which method to invoke. Althought, the DLR does to a reasonably good job of caching this information at the call site, which can amortize the cost if you will invoke the method multiple times.