I found a good example of when not to try to use generics.
I was obviously back in my C++ mindset when I tried to do this:
public class Test
{
private void Func(string s) {/*do something*/}
private void Func(int i) {/*do something*/}
public void GenericFunc<T>(T t)
{
Func(t);
}
public void main()
{
GenericFunc<string>("String");
GenericFunc<int>(1);
}
}
This (should) produces the nice compile errors:
CS1502: The best overloaded method match for 'Test.Func(string)' has some invalid arguments
CS1503: Argument '1': cannot convert from 'T' to 'string'
The reason I was trying to write this code was to reduce the amount of code I was writing. I had inconviently consolidated several functions that did the same thing into one Generic function, however, there was one specific difference for each method - the call to Func(Type) which was radically different between types. So even though I had declared the functions for which I was using, we get a compile error because .NET requires generics to be fully generic. Converting the syntax to C++ and compiling as c++ would result in a happily running piece of code.
Here is the SDK documentation for it:
Differences Between C++ Templates and C# Generics (C# Programming Guide)
Reading the last key point:
C++ allows code that might not be valid for all type parameters in the template, which is then checked for the specific type used as the type parameter. C# requires code in a class to be written in such a way that it will work with any type that satisfies the constraints. For example, in C++ it is possible to write a function that uses the arithmetic operators + and - on objects of the type parameter, which will produce an error at the time of instantiation of the template with a type that does not support these operators. C# disallows this; the only language constructs allowed are those that can be deduced from the constraints.