Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Method overloading resolution and user-defined implicit conversions

I try to find some information about method overloading resolution in case of presence of user-defined implicit conversions and about conversions priority.

This code:

class Value
{
    private readonly int _value;
    public Value(int val)
    {
        _value = val;
    }

    public static implicit operator int(Value value)
    {
        return value._value;
    }

    public static implicit operator Value(int value)
    {
        return new Value(value);
    }
}

class Program
{
    static void ProcessValue(double value)
    {
        Console.WriteLine("Process double");
    }

    static void ProcessValue(Value value)
    {
        Console.WriteLine("Process Value");
    }

    static void Main(string[] args)
    {
        ProcessValue(new Value(10));
        ProcessValue(10);
        Console.ReadLine();
    }
}

Produces output:

Process Value
Process Value

So, It looks like compiler chosen user-defined conversion instead of built-in implicit conversion from int to double (built-in conversion is implicit due to info from this page https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit-numeric-conversions-table).

I tried to find something about this in specification, but with no success.

Why compiler selected ProcessValue(Value value) instead of ProcessValue(double value)

like image 418
Daniel Vlasenko Avatar asked Nov 12 '18 13:11

Daniel Vlasenko


1 Answers

In this case, the conversion between int -> double takes lower precedence because a user-defined implicit conversion between int -> Value exists.

See: User-defined operator implementations always take precedence over predefined operator implementations.

like image 191
Leonardo Herrera Avatar answered Nov 17 '22 08:11

Leonardo Herrera