List of objects of type I don't know yet C #

I have a problem designing my function so that it can act differently for different types. My function is used to create a list of objects with different types, so there would be no problem creating several similar functions, but if possible, I would like to avoid this in order to make my code a little shorter:

static const int FIRST_TYPE = 0; static const int SECOND_TYPE = 1; static const int THIRD_TYPE = 2; 

I use those int as an argument to the function:

 public void foo(int type) { List<TypeIDontYetKnow> deserialized; switch (type) { case FIRST_TYPE: deserialized = new List<A>(); break; case SECOND_TYPE: deserialized = new List<B>(); break; case THIRD_TYPE: deserialized = new List<C>(); break; } } 

Is it possible to achieve something like this?

+4
source share
2 answers

You need a general method

 public void foo<T>() { List<T> deserialized = new List<T>(); } 
+11
source

You can do this using a non-generic IList for deserialized , since List<T> implements it:

 IList deserialized; 

However, you should not do this. More information about what you are trying to achieve can help us offer you a better solution:

  • First, MBen's answer with a common method .
  • If A , B and C are mutually subclassed , you might not have to distinguish between types at compile time, but use List<ABCBase> in the first place.
+2
source

All Articles