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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With