LightStriker
LightStriker

Reputation: 21004

Are constraints taken into account while resolving generic method signature?

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?

Upvotes: 3

Views: 277

Answers (2)

Jules
Jules

Reputation: 1081

And you might also have a method like

 public MyClass Method<T>() 
    {
        // Do something specific to a myclass
    }

so the compiler wouldn't have an unambiguous choice.

Upvotes: -1

Reed Copsey
Reed Copsey

Reputation: 564413

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#.

Upvotes: 4

Related Questions