Are constraints taken into account when resolving the generic signature of the method?

advertisements

Assuming this:

public class GenericMethods
{
    public T Method<T>() where T : struct
    {
        // Do something specific to a struct
    }

    public T Method<T>() where T : class
    {
        // Do something specific to a class
    }
}

Is somehow invalid at compile time, because the two method take the same parameters. But would there really be a moment that the two methods would collide since the constraints are mutually exclusive? Would it be possible while resolving T that the software would be unable to choose one of the two methods?

How would someone make two generic methods of the same name and parameters that would differ if the generic type is a struct or a class?


No. Contraints are not taken into account. Neither are return types. This will not compile, and is not legal C#.

This is documented in 3.6 of the C# language spec:

The signature of a method specifically does not include the return type, the params modifier that may be specified for the right-most parameter, nor the optional type parameter constraints.

While the two methods are "logically" distinct, and couldn't conflict, as the constraints should make it clear which is being called, the C# language doesn't support this. The language designers decided that this was the way they chose to implement the rules for C#.