views:

29

answers:

1

I have an interface that is implemented in a customcontrol:

public interface IArrow{...}
pulblic class Arrow1:UserControl, IArrow{....}
pulblic class Arrow2:UserControl, IArrow{....}

Then i have my form that shows the arrows doing:

Arrow1 arr1=new Arrow1();
Arrow2 arr2=new Arrow1();
this.Controls.Add(arr1);
this.Controls.Add(arr2);

But I want to be able to do this:

IArrow arr1=new Arrow1();
IArrow arr2=new Arrow1();
this.Controls.Add(arr1);

The problem is that I need to cast to add to controls:

this.Controls.Add((Arrow1)arr1);

So my question is what interface my interface has to implement to be able to add into controls? So my IArrow would be:

public interface IArrow:InterfaceToAddToControls {...}

(this is a summary not the full code as you can imagine)

+1  A: 

The argument of the Control.ControlCollection.Add() method must be of type Control. That's not an interface type. Your control is already derived from Control, no cast is needed. You'll just need a separate local variable, no way around that:

  var ctl = new Arrow1();
  this.Controls.Add(ctl);
  IArrow arr1 = ctl;

Or a little helper method:

private IArrow AddArrow(Control ctl) {
  this.Controls.Add(ctl);
  return ctl as IArrow;
}
...
  IArrow arr1 = AddArrow(new Arrow1());
Hans Passant