Dynamically creating a class from it's string name

B

blue

I have a class called "MyClass". At runtime, I don't know that the class is
of type MyClass but I do know the string name of the class. Is there a way
to create an instance of a class when I only know it's name?

I was looking at:

Type myType1 = Type.GetType("System.Int32");
myType1 = 10; // error because myType is of type Type, not System.Int32
myType1.ToString(); // prints out "System.Int32"

I need to have an instance of my object and call its methods, not an
instance of Type.

Any help will be much appreciated.

Thanks.
 
N

Nicholas Paldino [.NET/C# MVP]

blue,

You will want to create an instance, you can use the static
CreateInstance method on the Activator class. However, to access it's
methods, you will have to cast the instance to the type, or you will have to
cast it to a base type/interface it implements. This is needed because you
need some sort of known type definition to access properties or call
methods.

Hope this helps.
 
J

Jon Skeet [C# MVP]

blue said:
I have a class called "MyClass". At runtime, I don't know that the class is
of type MyClass but I do know the string name of the class. Is there a way
to create an instance of a class when I only know it's name?

Yup - look at Activator.CreateInstance, or if you want to use specific
constructors, you can call Type.GetConstructor and the Invoke the
constructor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top