How to initialize class object from given string?

L

Ladislav Kepl

I would like to initialize new instance of class
"EWC.EWCWebCustomControls.EwcImgButton" defined in string and then work with
the object of this class, I tried this:

Type myType =
System.Reflection.Emit.TypeBuilder.GetType("EWC.EWCWebCustomControls.EwcImgB
utton");

ctrl = (myType)Convert.ChangeType(ctrl,myType);

but the .NET framework doesn't compile it ane send the build message:

logic.cs(185): The type or namespace name 'myType' could not be found (are
you missing a using directive or an assembly reference?)


Do some body know how to create this instance of class? Thank you in
advance?

LK
 
J

Jon Skeet [C# MVP]

Ladislav Kepl said:
I would like to initialize new instance of class
"EWC.EWCWebCustomControls.EwcImgButton" defined in string and then work with
the object of this class, I tried this:

Type myType =
System.Reflection.Emit.TypeBuilder.GetType("EWC.EWCWebCustomControls.EwcImgB
utton");

Are you actually using TypeBuilder, or do you really mean just

Type.GetType(...);

?
ctrl = (myType)Convert.ChangeType(ctrl,myType);

If you want to create a new instance of the class, ChangeType isn't
what you want at all - look at Activator.CreateInstance instead.

Also, you can't cast to (myType) because myType is the name of a
variable, not a class. How is ctrl declared?
 
D

Dmitriy Lapshin [C# / .NET MVP]

Hi Ladislav,

Take a look at the Activator class and its CreateInstance method. It should
do the job for you.
 

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