Name of type to class instance?

  • Thread starter Thread starter Smokey Grindle
  • Start date Start date
S

Smokey Grindle

Is it possible to create an object of a specific type just by knowing its
name as a text string? Say I have the string

System.Windows.Forms.Textbox how would I go about turing that string into an
object of that type? I think its possible with reflection, but not sure
how... thanks!
 
Smokey said:
Is it possible to create an object of a specific type just by knowing its
name as a text string?

Almost certainly.
I think its possible with reflection, but not sure how...

As soon as you start reaching for the Reflection tool box, take a step
back and ask yourself if there's not a better way to do what you need.

What is it that you want to achieve? (never mind how, for now)

Regards,
Phill W.
 
Well we know for certain we have to create objects on the fly based off of a
type name specified in a database row... so right now we have the object
type... just need to create the object
 
Is it possible to create an object of a specific type just by knowing its
name as a text string? Say I have the string

System.Windows.Forms.Textbox how would I go about turing that string into an
object of that type? I think its possible with reflection, but not sure
how... thanks!

Topics to look at in the documentation:

Type.GetType
Activator.CreateInstance

That should be enought to get you started.
 
awesome, thanks!

Tom Shelton said:
Topics to look at in the documentation:

Type.GetType
Activator.CreateInstance

That should be enought to get you started.
 
Well we know for certain we have to create objects on the fly based off of a
type name specified in a database row... so right now we have the object
type... just need to create the object

In addition to the others, if you are using serializable controls you
can store the searilized data into the database and then deserialize
the data back into the control. This way you don't have to worry about
setting all the properties.

Thanks,

Seth Rowe
 
Smokey said:
Well we know for certain we have to create objects on the fly based off of a
type name specified in a database row... so right now we have the object
type... just need to create the object

Ah ha!
That's one of the Good Reasons for doing this.

As Tom said, Type.GetType and Activator.CreateInstance.

This will work well for Framework-defined Types but watch out when you
start trying to use Types defined in /your own/ assemblies - whatever
process is doing all this has to be able to "get hold of" (i.e. Load)
the defining Assemblies. Can make for some fun deployment issues.

HTH,
Phill W.
 
Back
Top