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 is mutually exclusive, why this does not compile:

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

The compiler states: "The type already defines a member named" Do "with the same parameter types.", But T and T do not match here. One of them is related to structures, the other to class restrictions. A function call must always be solvable. Are there countable examples?

+6
c # type-systems
source share
2 answers

General restrictions are not accepted as part of overload compliance. This is the same as the 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 cases, overload negotiation rules only consider parameter types, ignoring additional information such as restrictions and return type.

+3
source share

No, types can never be both. The code does not work because the general parameters ( <T> , that is, not T obj ) do not have the concept of "overload". Also, there is nothing like a specialized specialization in C ++.

+1
source share

All Articles