Sunday, January 7, 2018

Overload in Depth


using System;

class Test
{
    static void Foo(int x)
    {
        Console.WriteLine("Foo(int x)");
    }

    static void Foo(double y)
    {
        Console.WriteLine("Foo(double y)");
    }
    
    static void Main()
    {
        Foo(10);
    }
}

This is absolutly fine and Foo(int x) will be printed. If we remove the first method than method of double will be called.
Here compiler decides which conversion is better so in this case int to int is better than int to double.
So fist method wins.

Second case


using System;

class Test
{
    static void Foo(int x, int y)
    {
        Console.WriteLine("Foo(int x, int y)");
    }

    static void Foo(int x, double y)
    {
        Console.WriteLine("Foo(int x, double y)");
    }

    static void Foo(double x, int y)
    {
        Console.WriteLine("Foo(double x, int y)");
    }
    
    static void Main()
    {
        Foo(5, 10);
    }
}

Here first method will win since it  beat second method on second parameter and third method on first
parameter.


Third case

using System;

class Test
{
    static void Foo(int x, double y)
    {
        Console.WriteLine("Foo(int x, double y)");
    }

    static void Foo(double x, int y)
    {
        Console.WriteLine("Foo(double x, int y)");
    }
    
    static void Main()
    {
        Foo(5, 10);
    }
}

Here no method wins outright, the compiler will report an error:
Error:
error CS0121: The call is ambiguous between the following methods or
properties: 'Test.Foo(int, double)' and 'Test.Foo(double, int)'

No comments:

Followers

Link