Why can't I define an implicit translation operator from an interface to a class?

Tell me the interface

public interface ISomeControl
{
    Control MyControl { get; }
    ...
}

Is it possible to define something like this:

public static implicit operator Control(ISomeControl ctrl)
{
    return ctrl.MyControl;
}

Or rather, why can't I do this in C #?

+6
source share
2 answers

What if you have a subclass Control, and this subclass implemented the interface ISomeControl.

class SomeControl : Control, ISomeControl {}

The listing will now be mixed - the built-in upcast and your custom conversion. Therefore, you cannot provide custom conversions for interfaces.

+6
source

You cannot do this.

The C # specification says:

6.4.1 Allowed custom conversions

# . , . S T, S T - , S0 T0 , S0 T0 S T . S T, :

  • S0 T0 - .

  • S0, T0 - , .

  • S0, T0 .

  • , S T T S.

- .

public class Control
    {
        public static Control FromISomeControl(ISomeControl ctrl)
        {
            return ctrl.MyControl;
        }
    }
+1

All Articles