Search code examples
c#.netoverloading

The call is ambiguous between the following methods or properties


Suppose I have these two ctors:

public SomeClass(string a, Color? c = null, Font d = null)
        {
            // ...
        }

public SomeClass(string a, Font c = null, Color? d = null)
        {
            // ...
        }

~and I do this:

SomeClass sc = new SomeClass("Lorem ipsum");

I'll get this: "Error 1 The call is ambiguous between the following methods or properties [...]"

It seems apparent to me that it doesn't matter which one I refer to as the end result is the same (at least in this particular case, and to me that's all that matters right now), so what are my options to getting around this?

EDIT 1: @oltman: Simplified example.

I just want to be able to write

[...] new SomeClass("Lorem", Color.Green)

instead of

[...] new SomeClass("Lorem", null, Color.Green)

Solution

  • Both constructors take the same number of arguments, but in a different order. Since you have specified default values for the two constructor parameters the compiler cannot distinguish between the two overloads when the second argument is not supplied.

    I would advise you to remove the existing constructors and replace with the following:

    public SomeClass(string a, Color? color, Font font)
    {
        // constructor implementation
    }
    
    public SomeClass(string a) : this(a, null, null) {}
    public SomeClass(string a, Color color) : this(a, color, null) {}
    public SomeClass(string a, Font font) : this(a, null, font) {}