views:

95

answers:

2

Dim a as Type=GetType(className) would gimme the type. But I have only the name of the class as string. I want something like GetType("class1") which would return the type.

+3  A: 
Type.GetType("class1")
Romain Verdier
Only works when class1 is in the global namespace.
Peter Lillevold
@Peter, sure, but it's just what's asked. Far more important is that it only works for type defined in the mscorlib or in the assembly containing the call to Type.GetType.
Jb Evain
A: 

Both Type.GetType(...) and Assembly.GetType(...) expects a fully qualified type name. Thus, only passing in the class name without its namespace will not yield the Type.

If you make sure to include the namespace like this:

Type.GetType("Fully.Qualified.Namespace.class1")

will yield the same result as GetType(class1).

Update: if you don't know the namespace of your class, you could do a search (using Linq mind you) on types in the current assembly:

GetType().Assembly.GetTypes().First(type => type.Name == "AssemblyModuleTests")

I assume this is a slower operation than looking up types using fully qualified names since GetTypes() enumerates all types in the assembly.

Peter Lillevold
You could combine the second query with AppDomain.CurrentDomain.GetAssemblies() to add scope to the search...
Roger Lipscombe
@Roger - surely. It would add even more to the burden though, since you would load all possible types in all loaded assemblies. So without knowing more about the scenario I wouldn't recommend it...
Peter Lillevold