Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a List of classes in C#?

In Java I am able to have a list of classes like:

List<Class>

But how do I do this in C#?

like image 261
user1592512 Avatar asked Dec 15 '22 05:12

user1592512


1 Answers

Storing the class types

If you mean a list of actual classes, not instances of a class, then you can use Type instead of Class. Something like this:

List<Type> types = new List<Type>();
types.Add(SomeClass.GetType());
types.Add(SomeOtherClass.GetType());

Instantiating the types

To actually instantiate a class given a classes Type you can use Activator or reflection. See this post for information on that. It can get a little complicated however when the compiler doesn't know about the constructors/parameters and such.

// Create an instance of types[0] using the default constructor
object newObject = Activator.CreateInstance(types[0]);

Or alternatively

// Get all public constructors for types[0]
var ctors = types[0].GetConstructors(BindingFlags.Public);

// Create a class of types[0] using the first constructor
var object = ctors[0].Invoke(new object[] { });
like image 110
Daniel Imms Avatar answered Dec 26 '22 14:12

Daniel Imms