tags:

views:

49

answers:

2

If not and the set of reference types and value types are mutually exclusive, why doesn't this compile:

public static void Do<T>(T obj) where T : struct { }
public static void Do<T>(T obj) where T : class { }

The compiler states: "Type already defines a member called 'Do' with the same parameter types.", but T and T are not the same here. One is constrained to structs, the other is constraint to classes. A call to the function should always be resolvable. Are there counter examples?

+3  A: 

The generic constraints are not being taken as part of the overload match. It is the same as return type.

For example, this will lead to the same error (overloads differ only in return type):

public static int Do<T>(T obj) { }
public static bool Do<T>(T obj) { }

In both of these cases, the rules for matching an overload take into account only the parameters types, ignoring additional information such as constraints and return type.

Elisha
+1  A: 

No, types can never be both. The code fails because generic parameters (the <T>, that is, not the T obj) have no "overloading" concept. Nor is there anything resembling C++ template specialisation.

Marcelo Cantos
Although you could tie things in knots over boxed value-types ;)
Marc Gravell