Muhammad Ahsen Haider
Muhammad Ahsen Haider

Reputation: 144

C# Function Overloading : Ambiguous Call

Getting the ambiguous call as arrangement of parameters are different: short,int / int,short /byte,int / int,byte

As Function signature is:

1.Number of arguments/parameters

2.Type of arguments/parameters

3.Arrangement of arguments/parameters

Why the call is ambiguous ? should it belongs to the similar type ?...

code:

class Program
{
    static void Main(string[] args)
    {

        test abbb = new test();
        //abbb.add(2.2f,1);
        // abbb.add(2,2.2f);
        abbb.add(255,1);
        abbb.add(1,256);
        Console.ReadLine();
    }
}

class test
{
    public int add(byte i , int f) {
       return i + f;
    }
    public int add(int i, byte f)
    {
        return i + f;
    }
    public int add(short i, int f)
    {
        return i + f;
    }
    public int add(int i, short f)
    {
        return i + f;
    }
}

Upvotes: 0

Views: 1156

Answers (3)

Muhammad Ahsen Haider
Muhammad Ahsen Haider

Reputation: 144

class Program
   {       
    static void Main(string[] args)
    {           
        test abbb = new test();

        Console.WriteLine(abbb.add(32767, 32770)); //short , int
        Console.WriteLine(abbb.add(32770, 32767)); //int ,short
        Console.WriteLine(abbb.add(255, 32770)); // byte,int
        Console.WriteLine(abbb.add(32770, 255)); // int,byte

        Console.ReadLine();
    }
}
class test
{       
    public int add(byte f, int i)
    {
        return i + f;
    }

    public int add(int i, byte f)
    {
        return i + f;
    }
    public int add(short i, int f)
    {
        return i + f;
    }
    public int add(int f, short i)
    {
        return i + f;
    }
}

No ambiguity due to mentioned specific range of types...

Upvotes: 0

MikeDub
MikeDub

Reputation: 5283

By default, any 'Magic Number' will be treated as an Integer, but sometimes for ease of use the compiler can convert to another number format implicitly if it has enough information to do so. In order to get around the ambiguous calls, you would be best explicitly defining typed variables for the numbers first, then passing them into the functions to remove any ambiguity.

Upvotes: 3

user5055454
user5055454

Reputation: 75

It is ambiguous because C# does not know which of the two numbers is which of the types. Both 1 and 256 may a be a short and both may be an int. You may use explicit casting to "choose" one of the methods.

Upvotes: -3

Related Questions