Why Implicit Conversion Operator does not work for Wrapper Types that feature Generics and Interfaces and fails with CS1503? #8263
-
Consider the following code: public class Class : IInterface { }
public interface IInterface { }
public readonly struct Wrapper<T> {
public Wrapper(T? value) { Value = value; }
T? Value { get; }
public static implicit operator Wrapper<T>(T? value) => new(value);
}
public static class Test {
public static void UseWrapperViaInterafce(Wrapper<IInterface?> value) { }
public static void UseWrapperViaClass(Wrapper<Class?> value) { }
public static void Test() {
IInterface instanceAsInterface = new Class();
UseWrapperViaInterafce(instanceAsInterface ); // <-- CS1503: cannot convert from 'IInterface' to 'Wrapper<IInterface?>'
Class instanceAsClass = new Class();
UseWrapperViaInterafce(instanceAsClass ); // <-- Works
UseWrapperViaClass(instanceAsClass ); // <-- Works
}
} What I am trying to understand is why when the Are there any plans to ease this limitation? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
No interfaces can have a user defined operator to a type defined like this. THat's because the end (or subclass) type may truly implement htat interface). In which case, instead of the actual runtime check and downcast, it would go through this user case instead. Consider this trivial example: interface IFoo
{
}
class C
{
public static implicit operator C(IFoo foo) => new C(...);
}
class D : C, IFoo
{
}
IFoo i = new D();
C c = (C)i; // this needs to not call through the conversion operator (which would create a new C), but instead actually just downcast properly.
Unlikely. Casting interfaces to a base class only going through the runtime is deeply part of our language and something we are not likely to ever change. |
Beta Was this translation helpful? Give feedback.
No interfaces can have a user defined operator to a type defined like this. THat's because the end (or subclass) type may truly implement htat interface). In which case, instead of the actual runtime check and downcast, it would go through this user case instead.
Consider this trivial example:
Unlikely. Casting interfaces to a base class only going through the runti…