Create an object on the fly knowing just an object type

  • Thread starter Thread starter Just D.
  • Start date Start date
J

Just D.

All,

Do we have a simple way to Create an object on the fly knowing just an
object type? The usual design-time way is to write a code something like
this:

CObjectType obj = new CObjectType();

That's simple. But to create any object knowing its object type on the fly
is looking like a problem. I'll try to explain the idea.

We have some base class with the method:

Deserialize(string sXML, ref obj, System.Type systemtype)
{
....
}

The idea is to create any object of required type, the type should be
defined through the interface, then to do some appropriate steps to get the
data from the XML string and assign all required properties of the created
object. The idea is simple, but realization... The worst scenario is to use
a switch by systemtype and create all required objects inside an appropriate
switch case. The method is terrible because it's not nice, looking terribly
and absolutely not flexible. But to do the method universal we need to
create a new object on the fly using something like:

systemtype obj = new systemtype();

where "systemtype" is the variable received as a method parameter.

The problem that writing this we're getting a non-workable code.

Any idea or solution? Maybe we could use a virtual method to do this thing
or some other trick?

Thanks,
Just D.
 
System.Reflection.Assembly.CreateInstance is one way, notice that you need
to know the assembly in which the object resides.

If your Deserialize method allows for external objects, you will need to
save the name of the assembly as well as the name of the type, you can then
use Assembly.Load to load the assembly after which you can use
Assembly.CreateInstance.

There are other ways to create an object given its type, you can use
Assembly.GetType() which return you a Type object, from this Type object you
can obtain a constructor by using Type.GetConstructor, you can also use the
Type object to call any method after the instance is created.

Check out the System.Reflection namespace, you will find tons of stuff
there.
 
Back
Top