Context: .NET 3.5, VS2008. I\'m not sure about the title of this question, so feel free to comment about the title, too :-)
Here\'s the scenario: I have several cla
You could subclass List<T>
or some other collection class and use the where
generic type constraint to limit the T
type to be only IStartable
classes.
class StartableList<T> : List<T>, IStartable where T : IStartable
{
public StartableList(IEnumerable<T> arr)
: base(arr)
{
}
public void Start()
{
foreach (IStartable s in this)
{
s.Start();
}
}
public void Stop()
{
foreach (IStartable s in this)
{
s.Stop();
}
}
}
You could also declare the class like this if you didn't want it to be a generic class requiring a type parameter.
public class StartableList : List<IStartable>, IStartable
{ ... }
Your sample usage code would then look something like this:
var arr = new IStartable[] { new Foo(), new Bar("wow") };
var mygroup = new StartableList<IStartable>(arr);
mygroup.Start(); // --> calls Foo's Start and Bar's Start