Say that you're writing a library to display things on the screen, so you create an IDisplayable
interface. This interface has one method to create a control from the object: displayable.GetControl()
.
You want to create your own list type that can be displayed: MyList<T>
. Now this list can only be displayed if T
is an IDisplayable
, so you could ask in the MyList class that T should implement IDisplayable. But you also want to use this list type in some places when T is not IDisplayable (and as a result this list will not be displayable). So is it possible to say that MyList implements IDisplayable if T implements IDisplayable? I would also be happy if MyList<T>
always implements IDisplayable but throws an exception at runtime if you try to call GetControl()
if T is not IDisplayable, but I'd like to know if there's a statically type-safe way to do it. Can this be done? Or am I looking at the wrong solution?
Edit:
I agree with the suggestions so far that MyList may have too many responsibilities. My original idea was to create a MyDisplayableList<T> : MyList<T> (where T : IDisplayable)
.
The problem with this approach is that I have a lot of methods that take a MyList and return a MyList (for example methods like Select in Linq). So if I use select on an MyDisplayableList I get back a MyList and them I'm unable to display it even though it is a MyList...is there a type safe way to handle this problem in C#?