I noticed a difference between the behavior of a custom implicit conversion to int and a user-defined implicit conversion to an arbitrary MyStruct structure when using operator== .
If I have:
public struct IntA { public IntA(int value) { m_value = value; } public static implicit operator int(IntA a) { return a.m_value; } private int m_value; } public struct IntB { public IntB(int value) { m_value = value; } public static implicit operator int(IntB b) { return b.m_value; } private int m_value; }
Then the following code compiles:
{ var a = new IntA(3); var b = new IntB(4); bool equal = (a == b);
This uses my custom implicit operator int for IntA and IntB to convert to int , and then calls operator==(int, int) .
However, if I have:
public struct MyStruct { public MyStruct(int value) { m_value = value; } public static bool operator==(MyStruct lhs, MyStruct rhs) { return lhs.m_value == rhs.m_value; } public static bool operator!=(MyStruct lhs, MyStruct rhs) { return lhs.m_value != rhs.m_value; } private int m_value; } public struct MyStructA { public MyStructA(int value) { m_value = new MyStruct(value); } public static implicit operator MyStruct(MyStructA a) { return a.m_value; } private MyStruct m_value; } public struct MyStructB { public MyStructB(int value) { m_value = new MyStruct(value); } public static implicit operator MyStruct(MyStructB b) { return b.m_value; } private MyStruct m_value; }
Then the following code does not compile:
{ var a = new MyStructA(3); var b = new MyStructB(4); bool equal = (a == b);
I expected it to do the same as in the previous example, and use my custom implicit operator MyStruct to convert to MyStruct , and then call operator==(MyStruct, MyStruct) .
This is not true. Why not? What is the difference between the two cases from a compiler point of view?
source share