tags:

views:

87

answers:

3

i have the following class:

class MyClass{  
{  

and the following string:

string s="MyClass";  

how can i get the Type of the class using string s as such:

Type t = typeof(MyClass); //but i need to use s instead.      

i have already tried

Type type = Type.GetType(s); //the result is null
+5  A: 

with googeling i've found this

Type type = Type.GetType(fully qualified class name string);

from msdn:

typeName: The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

Return Value The type with the specified name, if found; otherwise, nullNothingnullptra null reference (Nothing in Visual Basic).

so, ... i believe it was not found when you get null as the result

for more info for AssemblyQualifiedName

to get an idea of your fully qualified name just do

typeof(MyClass).FullName
typeof(MyClass).AssemblyQualifiedName
Andreas Niedermair
This should work for him. The result NULL can be returned if there was no such type in that assembly at all.
nihi_l_ist
that's excatly what i quoted from msdn :)
Andreas Niedermair
To clarify: The string s must be the fully qualified typename, i.e. something like "MyCompany.MyApplication.MyClass", or if it is in the executing assembly you may only need "MyApplication.MyClass". Just using "MyClass" on its own will not work.
Jason Williams
how can i get the assembly-qualified name of a class?
scatman
from the msdn article: `For example, the fully qualified name for a class might look like this: TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly` ... i suggest you might read through the article!
Andreas Niedermair
+1  A: 

GetType should work with the qualified name. Refer to the following thread (which includes some insights from Jon Skeet)...

Demi
+1  A: 

If you are always in the same assembly you can use Assembly.GetType so you don;t have to store a string with the assembly name.

this.GetType().Assembly.GetType("MyNamespace.MyClass");
Igor Zevaka