Luiscencio
Luiscencio

Reputation: 3965

Declaring a List of types

I want to declare a list containing types basically:

List<Type> types = new List<Type>() {Button, TextBox };

is this possible?

Upvotes: 34

Views: 56801

Answers (5)

Greg
Greg

Reputation: 16680

List<Type> types = new List<Type>{typeof(String), typeof(Int32) };

You need to use the typeof keyword.

Upvotes: 4

Adam Sills
Adam Sills

Reputation: 17062

You almost have it with your code. Use typeof and not just the name of the type.

List<Type> types = new List<Type>() {typeof(Button), typeof(TextBox) };

Upvotes: 14

Yannick Motton
Yannick Motton

Reputation: 36031

Try this:

List<Type> types = new List<Type>() { typeof(Button), typeof(TextBox) };

The typeof() operator is used to return the System.Type of a type.

For object instances you can call the GetType() method inherited from Object.

Upvotes: 71

3Dave
3Dave

Reputation: 29061

Use a typed generic list:

List<Type> lt = new List<Type>();

Upvotes: 1

Matt Brunell
Matt Brunell

Reputation: 10399

Yes, use List<System.Type>

var types = new List<System.Type>();

To add items to the list, use the typeof keyword.

types.Add(typeof(Button));
types.Add(typeof(CheckBox));

Upvotes: 5

Related Questions