fz8975
fz8975

Reputation: 45

C# overloading ambiguity

class Program
{
    public void x(int a, float b , float c) 
    {
        Console.WriteLine("Method 1 ");
    }
    public void x(float a, int b,int c) 
    {
        Console.WriteLine("Method 2 ");
    }
    static void Main(string[] args)
    {
        Program ob = new Program();
        ob.x(1, 2, 3);
    }
}

ob.x(1,2,3) is showing

Error 1 The call is ambiguous between the following methods or properties: 'OverloadDemo.Program.x(int, float, float)' and 'OverloadDemo.Program.x(float, int, int)'

C:\Users\Public\Videos\SampleVideos\Projectss\OverloadDemo\OverloadDemo\Program.cs 25 13 OverloadDemo

Method 2has two arguments ofinttype andMethod 1has two argumets ofint` type. So Method 1 should be favoured.

Why is there an error ?

Upvotes: 0

Views: 125

Answers (2)

Haney
Haney

Reputation: 34922

Due to the implicit conversion of int to float, the compiler cannot discern which method you intended to call. You'd have to be more intentional with the types:

ob.x(1f, 2, 3);

vs

ob.x(1, 2f, 3f);

Upvotes: 2

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

A simple solution to this, would be while you're going to consume the method with this signature public void x(int a, float b , float c), call it like this,

ob.x(1, 2.0f, 3.0f); // convert them to float

This would make sure that these are sent as float and the first param is sent as a integer. A sample to test this, is here, do test it out. https://dotnetfiddle.net/9yaKJa

Upvotes: 0

Related Questions