Dlaor
Dlaor

Reputation: 3020

Is there a way to turn a string into a Type object?

Let's say I have this basic string...

string a = "Entity";

And this Type object...

Type t;

Is there any way to make this Type object reference the type Entity by reading a?

Exanple: if a changes to Prop, it would create a Type object which references the Prop type. t would then be equal to typeof(Prop).

Upvotes: 1

Views: 162

Answers (3)

KeithS
KeithS

Reputation: 71565

Yes. There is a static Type.GetType() method that takes a string and returns a Type object representing the type with the name given by the string.

Understand that this will search all referenced namespaces, and there are several classes named, for instance, "TextBox" (in WFA, WPF and ASP namespaces). So, you must fully qualify your type name in order for the method to get the correct type.

Upvotes: 6

Pondidum
Pondidum

Reputation: 11617

This will create an instance of the class for you, although you cannot cast it to the type specified (unless you have a base object, or know it implements an interface):

public class Testing
{
    private void Test()
    {
        var name = "A";

        var type = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Name == name).FirstOrDefault();
        var obj = Activator.CreateInstance(type);
    }
}
private class A
{ 
}

Upvotes: 1

jason
jason

Reputation: 241583

Yes, you can use Type.GetType(string).

Note:

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.

Beware the additional remarks on the linked MSDN page.

Upvotes: 3

Related Questions