6

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

List<Class>

But how do I do this in C#?

Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
user1592512
  • 423
  • 2
  • 4
  • 7

3 Answers3

14

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[] { });
Community
  • 1
  • 1
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
1

The same basic syntax works in C#:

List<YourClass> list = new List<YourClass>();

This requires you to have using System.Collections.Generic; at the top of your file, which is the namespace which provides most of the generic collections.

If you are attempting to store a list of types, you can use List<System.Type>. Instances of those types could then be constructed via Activator.CreateInstance (which accepts the type) as needed.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0
    // Create the list
    List<ClassName> classList = new List<ClassName>();

    // Create instance of your object
    ClassName cn = new ClassName();

    // Add the object to the list
    classList.Add(cn);
pkremer
  • 56
  • 3