Can a type be instantiated at runtime?

  • Thread starter Thread starter Will Pittenger
  • Start date Start date
W

Will Pittenger

I have a function that I want to be passed a System.Type. If the type is
derived from a specific class, I want to have the function instantiate an
instance. With MFC, this would be a snap (provided the class was created
with the DYNCREATE macros).

Can this be done in C#?
 
...
I have a function that I want to be passed a System.Type. If the type is
derived from a specific class, I want to have the function instantiate an
instance. With MFC, this would be a snap (provided the class was created
with the DYNCREATE macros).

Can this be done in C#?

Sure...

object GetInstance(Type type)
{
return Activator.CreateInstance(t);
}

However, you might need to look closer to the reflection in .NET, as you
might go into some traps where some types doesn't have default constructors,
etc.


// Bjorn A
 
Going beyond what was asked....

Its a often programming situation these days that we might need to create an
object based off a string (ie an attribute in an xml file). This is also
easy to do,

Stiring sType = "{classname}, {assemblyname}";
Type type = Type.GetType(sType);
object x = Activator.CreateInstance(type);

Joe
MCAD
SRE (Simple Rule Engine)
https://sourceforge.net/projects/sdsre/
 
Thanks anyway, but as soon as I posted, I realized that passing the type did
not make sense. I tried to cancel the post, but I guess you saw it anyway.
 
I should note that I still need an answer to my "Adding cursor resource to
project" post. If you know of a solution, please respond to that thread.
 
Back
Top