Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a type be a reference type and a value type at the same time?

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?

like image 567
Rauhotz Avatar asked Oct 23 '10 08:10

Rauhotz


2 Answers

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.

like image 144
Elisha Avatar answered Nov 11 '22 17:11

Elisha


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.

like image 30
Marcelo Cantos Avatar answered Nov 11 '22 18:11

Marcelo Cantos