Which of these equality cases with conversion is a mistake, if any?

Consider the following:

using System;

struct FooEnum {
    public static implicit operator TypeCode(FooEnum foo) { return TypeCode.Empty; }
}

struct FooDelegate {
    public static implicit operator EventHandler(FooDelegate foo) { return null; }
}

struct FooInt {
    public static implicit operator int(FooInt foo) { return 0; }
}

class Foo {
    public static void Main(string[] args) {
        Console.WriteLine(new FooEnum() == new FooEnum());  // CS0019
        Console.WriteLine(new FooDelegate() == new FooDelegate());  // OK
        Console.WriteLine(new FooInt() == new FooInt());    // OK
    }
}

When compiled, this will create

Error CS0019: The operator '==' cannot be applied to operands of type FooEnum and FooEnum

Tested with VC # 2005 8.0.50727.8745, csc 4.6.1586.0, Roslyn 1.3.2 and Roslyn 2.0.0-rc2. The result is the same in all cases.

In the C # 5.0 Language Specification , Β§7.10:

For an operation of the form x op ywhere op is the comparison operator, overload resolution (Β§7.3.4) is used to select a specific implementation of the operator. The operands are converted to the parameter types of the selected operator, and the result type is the return type of the operator.

(Β§7.10.5), (Β§7.10.8) int (Β§7.10.1). (Β§7.3.4) , , Foo ,

... , , - . (Β§7.8 - Β§7.12). , , .

( " " , dynamic.)

, , , TypeCode (, , FooEnum ), , , FooDelegate , . (FooInt - , , .)

, FooDelegate ? , ( ) FooEnum ( )?

+4

Source: https://habr.com/ru/post/1664197/


All Articles