Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't it possible to define implicit cast operator from interface to class?

Say, I have an 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 that in C#?

like image 355
horgh Avatar asked Sep 21 '12 15:09

horgh


1 Answers

What if you had a subclass of Control, and that subclass implemented the ISomeControl interface.

class SomeControl : Control, ISomeControl {}

Now a cast would be ambiguous -- the built-in upcast, and your user-defined conversion. So you can't provide user-defined conversions for interfaces.

like image 103
Ben Voigt Avatar answered Oct 25 '22 18:10

Ben Voigt