Search code examples
c#nullabledefault-parameters

How to avoid ambiguous references with overridden methods with default parameters involving nullable types?


I have some methods like the following:

static public int GetInt(int _default = 0)
{
    // do work, return _default if error
}

static public int? GetInt(int? _default = null)
{
    // do work, return _default if error
}

I was hoping when using these methods as overrides that the method would be chosen also based on the variable I am using them to assign to:

int value1 = GetInt();
int? value2 = GetInt();

However this results in an "Ambiguous Invocation" error.

What can I do to avoid this?


Solution

  • The problem is that the return type is not part the signature of a method in C#. So you have to name the methods differently. Also, don't use underscore in parameter names.

    To quote MSDN on how method signatures work:

    The signature of a method consists of the name of the method and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.

    This is a way to resolve it. As you return the default of the type, you can just make it generic and use default(T).

        static void Main(string[] args)
        {
            int value1 = GetInt<int>();
            int? value2 = GetInt<int?>();
        }
    
    
        static public T GetInt<T>(T defaultValue = default(T))
        {
            bool error = true;
            if (error)
            {
                return defaultValue;
            }
            else
            {
                //yadayada
                return something else;
            }
        }