Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutally exclusive constraints on two methods with the same signature

Tags:

c#

So these two methods have the same signature but different constraints

public static void Method<T>(ref T variable) where T : struct { }

public static void Method<T>(ref T variable) where T : class { }

But they cannot be defined in a single class because they have the same signatures. But in this particular case they're mutually exclusive. (Unless I'm wrong about that)

I understand you can put additional constraints besides class and struct but you can't specify both struct and class on the same method. So why would this fail to compile?

like image 915
Buildstarted Avatar asked Jun 14 '12 19:06

Buildstarted


2 Answers

The generic constraints are not considered part of the method signature (thanks @Anthony for the link).

As far as the compiler is concerned you have a duplicate method - same numbers and types of parameters.

like image 87
Oded Avatar answered Sep 18 '22 07:09

Oded


Although the compiler could be smart enough to figure it out (which it appears not to be), you do not know what to do for object (as it can be class or struct).

like image 37
earlNameless Avatar answered Sep 21 '22 07:09

earlNameless