I have a custom control for a LayoutPanel that holds child controls. I want the ensure that all child controls contain a certain property from the Parent container of the layout panel. I attempted to use the following code to create various child controls which will ensure storage of the property ChartPropertyOwner, relying on inheritance to assume the type (Labels, Buttons, standard forms controls)
public partial class ManipControl : System.Windows.Forms.Control {
public ChartPropertySet ChartPropertyOwner { get; set; }
public ManipControl(ChartPropertySet _cps) {
ChartPropertyOwner = _cps;
InitializeComponent();
}
}
I initialize with the following statement:
Button btnManipDel= new ManipControl(_cps);
I receive the error:
Cannot implicitly convert type ‘ManipControl’ to ‘System.Windows.Forms.Button’
Why does implicit conversion fail and how do I resolve this?
ManipControl->System.Windows.Forms.Control
Button->System.Windows.Forms.Control
Button is not guaranteed to be a ManipControl
To resolve this, you can just explicitly cast to a Button.
I don’t know that this is the best thing to do as a Button != ManipControl. The only guaranteed functions will come from their base class of System.Windows.Forms.Control. That is the better class to cast to, and I believe will implicitly cast (but am not positive):
You might want to read up on Liskov’s Substition Principle and contravariance and covariance.