scatman
scatman

Reputation: 14555

Converting Strings to Class Names in c#

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

Upvotes: 1

Views: 9001

Answers (3)

user57508
user57508

Reputation:

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

Upvotes: 8

Igor Zevaka
Igor Zevaka

Reputation: 76520

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");

Upvotes: 1

Demi
Demi

Reputation: 6227

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

Upvotes: 1

Related Questions