0

Please consider the following snippet:

protected object GetArg(Dictionary<string, object> args, string argName)
{
    object arg;
    if (args.TryGetValue(argName, out arg))
    {
        return arg;
    }
    return null;
}
protected T GetArg<T>(Dictionary<string, object> args, string argName) where T : class
{
    return GetArg(args, argName) as T;
}
//following does not compile: 
//Type ... already defines a member called 'GetArg' with the same parameter types
protected T GetArg<T>(Dictionary<string, object> args, string argName) where T : struct
{
    Nullable<T> arg = GetArg(args, argName) as Nullable<T>;
    return arg.HasValue ? arg.Value : default(T);
}

Should not constraining the T parameter type to be mutually exclusive between above generic declarations be enough to guarantee unambiguity? Why are type constraints not considered by the compiler in this case? Is there something I'm missing?

slawekwin
  • 6,270
  • 1
  • 44
  • 57
  • 1
    C# language spec, section 3.6: "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.**" (My emphasis) – Damien_The_Unbeliever Oct 28 '15 at 08:19
  • I'm not sure I agree with the linked duplicate since this question seems to be about *declaring* two methods with identical signatures (except for type constraints) and the duplicate is about overload resolution. – Damien_The_Unbeliever Oct 28 '15 at 08:28

0 Answers0