Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous function/constructor call in C#

The following code causes a compiler error, as it is ambiguous call but the problem if we use object instead of ArrayList no error happens and the string version works fine; Do you have an explanation for that?

class A
{
    public A(string x)
    {
        Console.WriteLine("string");
    }
    public A(ArrayList x)
    {
        Console.WriteLine("ArrayList");
    }

}
    static void Main(string[] args)
        {
            A o = new A(null);
        }
like image 399
Ahmed Avatar asked May 19 '10 12:05

Ahmed


People also ask

How to fix ambiguous call to overloaded function?

There are two ways to resolve this ambiguity: Typecast char to float. Remove either one of the ambiguity generating functions float or double and add overloaded function with an int type parameter.

Why constructor is called special member function?

Answer: A constructor can be defined as a special member function which is used to initialize the objects of the class with initial values. It is special member function as its name is the same as the class name. It enables an object to initialize itself during its creation.

Should a ViewModel have a constructor?

At present, this means that every ViewModel must have a public constructor which has either no parameters or which has only string parameters.

What is ambiguity in constructor in C++?

ambiguous means the compiler found multiple “valid” choices and refused to make the choice for you. You need to add clarifying information (usually about types). It may be that the compiler is able to convert a value into a type that matches a constructor and can do this twice.


1 Answers

The reason your code works fine if you change the constructor that takes an ArrayList to take an object is that the C# compiler will pick the most specific type applicable. In the case of string/object, string actually derives from object and is therefore "more specific" and will be inferred by the compiler. With string versus ArrayList, it's apples and oranges: either can be null, but neither is more "specific" than the other.

like image 84
Dan Tao Avatar answered Oct 05 '22 02:10

Dan Tao