How to make a list of what an abstract class and interface (C #) implement?

Let's say I have a list of Tanks, Aircraft, and much more, that the usual thing that they implement is IHaveLocation, which is both an abstract class, and IHaveColor, which is an interface.

I want to make a list of them because I need to request a list based on these two interfaces.

How can I do it?

  • I can make a list of objects and then write (obj as IHaveLocation) and use its methods and (obj as IHaveColor) and use its methods. but it is very ugly!
  • I can make a list of IhaveLocation, and then I need to make only one of them (obj like IHaveColor). But it is also terrible.
  • I can create a new abstract class and then inherit from both, but I'm trying to avoid it.

is there any trick?

I want to do something like List<IHaveLocation and IHaveColor>

+4
source share
3 answers

As I mentioned in Reid's answers, you can use general methods to add both a tank and an airplane. Something like that:

 class TwoTypesList<T1, T2> { List<Tuple<T1, T2>> m_list = new List<Tuple<T1,T2>>(); public void Add<ConcreteT>(ConcreteT item) where ConcreteT : T1, T2 { m_list.Add(Tuple.Create<T1, T2>(item, item)); } } 

Then use will be:

  TwoTypesList<IHaveColor, IHaveLocation> list = new TwoTypesList<IHaveColor, IHaveLocation>(); Airplane a = new Airplane(); Tank t = new Tank(); list.Add(a); list.Add(t); 

The disadvantage, of course, is that you store the object twice. If you do not like this, then, of course, you can change the internal storage of the list as an object or only one of the interfaces.

+1
source

You can wrap this in a generic class with restrictions for both types:

 public class YourClass<T> where T : IHaveLocation, IHaveColor { List<T> items = new List<T>; public void Add(T item) { items.Add(item); } // ... } 

Methods in this class can then use both interfaces as needed, since the type is guaranteed to implement them.

+7
source

you can try something like:

 public class YourClass<T> where T : Ihavelocation, ihavecolor{ List<T> items = new List<T>; public void Add(T item){ items.Add(item); } } 
0
source

All Articles