0

I have an Interface IDataControl:

public interface IDataControl
{
    ...
}

Then, I have a class with a variable of List<IDataControl>.

List<IDataControl> items;


The problem is when I try to add elements of this collection in a "Controls" property of another form or another control:

panel.Controls.Add(items[i]);

The IDE says me that "The best overloaded method matching......" because "IDataControl" is not inherited from "Control".

I understand the error, and I kwnow that I can do some casting like:

panel.Controls.Add(   (Control)items[i]   );


But, I want to know if there is a "cleaner" way to do this, without requiring a casting, having also strict type verifying.



So, is it possible to indicate that "IDataControl" only can be implemented by Control derived objects?

public interface IDataControl where this : Control
{
    ...
}


Or, is it possible to declare a variable of a class and a interface?
Something like this:

Control:IDataControl item;
List<Control:IDataControl> items;




Thanks

HOO
  • 1

1 Answers1

0

As you already understood System.Windows.Forms.Control does know nothing about your interface.


public interface IDataControl where this : Control
{
    ...
}

You can't do that. It is Applied for generics type constraints Also interfaces can not be inherited from class. An interface has the following properties:

  • An interface is like an abstract base class: any non-abstract type that implements the interface must implement all its members.

  • An interface cannot be instantiated directly.

  • Interfaces can contain events, indexers, methods, and properties.

  • Interfaces contain no implementation of methods.

  • Classes and structs can implement more than one interface.

  • An interface itself can inherit from multiple interfaces.

What you need is perhaps next: When you create you controls, inherit them from your interface.

In this host control you need to create a method

private void AddDataControl(IDataControl dataControl)
{
   if(IDataControl is Control){
      //your logic
   }
   else{
      throw new ArgumentException();
   }
}

It's just general approach. Depends on your code.

Artiom
  • 7,694
  • 3
  • 38
  • 45