tags:

views:

685

answers:

3

I am having trouble writing a typeof statement which would be using a variable from a config file the code is like this

Type t = new typeof ("My.other.class" + configValue[0]);

configValue being the dynamic value I get from the app.config file.

The error I get is "type expected" it is fine if I type out the class directly so I am assuming my formatting is incorrect. How should this be written?

+15  A: 

The typeof keyword is for compile-time use. Use the Type.GetType(string) API instead.

HTH, Kent

Kent Boogaart
This won't work, unless the type is in the current assembly, or mscorlib. Otherwise, you need to supply the full assembly qualified name, not just namespace+type.
Reed Copsey
+2  A: 

To do this using just a namespace and class name (like in the question), you'll also need to know which assembly contains the class.

If the currently running assembly (or mscorlib) contains the Type, then you can use Type.GetType(string) to get the Type.

If the Type is contained in a different assembly (ie: a library), then you'll need to use Assembly.GetType instead. This requires having an Assembly instance, however, which can be retrieved via Assembly.Load, or using another type within the assembly.

Reed Copsey
You can still use Type.GetType. You just need the assembly-qualified type name. The API docs I linked to explain that.
Kent Boogaart
Yeah - My comment specified that, as well. You just can't load it with the syntax in the question (namespace + type), without using the assembly.
Reed Copsey
+2  A: 

Is this what you're looking for?

Type t = Type.GetType("spork");
object myspork = Activator.CreateInstance(t);
yodaj007