tags:

views:

157

answers:

5

I want to declare a list containing types basically:

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

is this possible?

+2  A: 

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));
Matt Brunell
I get an error : "Button is type but is used as a variable"
Luiscencio
A: 

Use a typed generic list:

List<Type> lt = new List<Type>();
David Lively
+17  A: 

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.

Yannick M.
Change the declaration to use `var` and you have my up-vote. :P
Noldorin
A slight variation of the scenario for posterity: if you have an instance/object and want to include its type in the same list use the object's .GetType() property -- e.g. see 'myButton' variable usage in the following:Button myBtn = new Button();List<Type> types = new List<Type>() { myBtn.GetType(), typeof(TextBox) };
John K
If this is declared somewhere else than in a method body type the var keyword isn't available. But yes you could (and should) use var in a method.
Yannick M.
Change the decleration to use var, and you have my down-vote. :P
Yuriy Faktorovich
hehe, indeed :-)
Yannick M.
+9  A: 

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) };
Adam Sills
+2  A: 
List<Type> types = new List<Type>{typeof(String), typeof(Int32) };

You need to use the typeof keyword.

Greg