Can I somehow have overloaded methods which differ only by generic type constraints?
This does not compile:
void Foo(T bar) wh
This is not possible.
Generic constraints are not considered to be part of the method signature for purposes of overloading.
If you want to allow both value types and reference types, why constrain at all?
Can I somehow have overloaded methods which differ only by generic type constraints?
No. It's not part of the method signature in terms of overloading, just like the return type isn't.
There are horrible ways of "pseudo-overloading" in some cases, but I wouldn't recommend going down that path.
For more information, you might want to read:
struct _Val_Trait<T> where T:struct { }
struct _Ref_Trait<T> where T:class { }
static void Foo<T>(T bar, _Ref_Trait<T> _ = default(_Ref_Trait<T>)) where T:class
{
Console.WriteLine("ref");
}
static void Foo<T>(T bar, _Val_Trait<T> _ = default(_Val_Trait<T>)) where T:struct
{
Console.WriteLine("val");
}
static void Main()
{
Foo(1); // -->"val"
Foo(DateTime.Now); // -->"val"
Foo(""); // -->"ref"
//but:
//Foo(null); - error: type cannot be inferred
}
An update. In C# 7.3 generic constraints are now part of overload decision.
So, this code will compile:
class Animal { }
class Mammal : Animal { }
class Giraffe : Mammal { }
class Reptile : Animal { }
static void Foo<T>(T t) where T : Reptile { }
static void Foo(Animal animal) { }
static void Main()
{
Foo(new Giraffe());
}