How to initialize class object from given string?

  • Thread starter Thread starter Ladislav Kepl
  • Start date Start date
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
 
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?
 
Hi Ladislav,

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