I am working on a utility that will have an interface for “Filters” with a number of implementations of that interface. Part of the interface will return an object of type Control that will be used in a UI for manipulating the filters.
I would like to be able to require that the returned control also implement another interface so that I can do things like request that the controls write back to the object that created them.
right now my code looks like:
public interface IFilter
{
Control Control();
}
I would like someting like:
public interface IFilterControl
{
...
}
public class FilterControl : Control, IFilterControl{}
public interface IFilter
{
...
FilterControl Control();
}
The above does not work because FilterControl does not actually implement IFilterControl.
If the above is not clear enough try to visualize how the imaginary keyword “implmenting” would work below
public interface IFilterControl
{
IFilter Filter{get;}
}
public interface IFilter
{
Control implmenting IFilterControl Control();
}
public interface FilterImpl : IFilter
{
Control implmenting IFilterControl Control(){
return new FilterControlImpl(this);
}
}
public partial class FilterImplControl : UserControl, IFilterControl
{
FilterImpl filter;
public FilterImplControl(FilterImpl filter)
{
this.filter = filter;
}
public IFilter Filter{get{return filter;}}
}
FilterImpl a_filter = GetAFilter();
Control implmenting IFilterControl ctl = a_filter;
panel.Controls.Add(ctl);
FilterImpl the_filter_indirectly = ctl.Filter;
Might want to look at using generics. They’ll let you place constraints on the type.
The where clause is a generic restraint and will require that T is always of type Control. It works for interfaces as well. That way, you know those methods or properties are always a derivative of Control and those expectations will show up in intellisense.
EDIT
Oh, just occurred to me that you can apply the generic solely at the method if you’d prefer.