C# compiler bug? Why doesn't this implicit user-defined conversion compile?
c#, compiler-construction
Solution
Apparently, implicit user defined conversions don't work when one of the types is an interface. From the C# specs:
6.4.1 Permitted user-defined conversions
C# permits only certain user-defined conversions to be declared. In particular, it is not possible to redefine an already existing implicit or explicit conversion. For a given source type S and target type T, if S or T are nullable types, let S0 and T0 refer to their underlying types, otherwise S0 and T0 are equal to S and T respectively. A class or struct is permitted to declare a conversion from a source type S to a target type T only if all of the following are true:
- S0 and T0 are different types.
- Either S0 or T0 is the class or struct type in which the operator declaration takes place.
- Neither S0 nor T0 is an interface-type.
- Excluding user-defined conversions, a conversion does not exist from S to T or from T to S.
In your first method, both types are not interface types, so the user defined implicit conversion works.
The specs are not very clear, but it seems to me that if one of the types involved is an interface type, the compiler doesn't even try to look up any user-defined implicit conversions.
Problem
Given the following struct: ``` public struct Foo<T> { public Foo(T obj) { } public static implicit operator Foo<T>(T input) { return new Foo<T>(input); } } ``` This code compiles: ``` private Foo<ICloneable> MakeFoo() { string c = "hello"; return c; // Success: string is ICloneable, ICloneable implicitly converted to Foo<ICloneable> } ``` But this code doesn't compile -- why? ``` private Foo<ICloneable> MakeFoo() { ICloneable c = "hello"; return c; // Error: ICloneable can't be converted to Foo<ICloneable>. WTH? } ```