I am attempting to set a System.Web.UI.Control object’s ID field. The control implements an interface, IChartControl, which does not have an ID property. I would like to retrieve the control as an IChartControl and set its ID field.
Should I do this?:
IChartControl chartControl = foo.GetChartControl();
(chartControl as Control).ID = foo.GetID();
chartControl.Bar();
or would it be equally right to add a new property to IChartControl named ‘ID’ so that when I set the ID field it sets Control’s ID field.
You do need to cast the object to the type that has the member you want to set, as you have in your code example.
Adding an
IDproperty toIChartControlwill work, but only do it if it makes sense in the context of this interface. This will indeed allow you to set theIDproperty without needed the cast.So long as the
IDin the interface and inControlare the same ones, you should be fine. Where you can get into trouble is if you try and use explicit interface implementations.