Instantiate new object based off a Type provided by custom EventArgs

I have a set of custom EventArgs that contain a Type, which in the course of this event occuring what type of object I need to instantiate.  I can't figure out how to create a new instance of an object of the specified type without doing a switch or if/else statement.  Is there something elegant I can use?

There's some real choppy pseudo-code below, but the general idea should come across.  Basically, I just want to set a public instance of an object derived from a common interface using the Type that is sent through the event args.  I'd like to do this without having to use a switch or if/else, as that defeats the purpose of having the event args.

(pseudo-code)
MyEventArgs : EventArgs
{
     public Type TypeYouNeedToCreate;
    ... this gets set appropriately on the constructor.
}

(on a page elsewhere in the application)
public IMyObject MyObject;
MyUserControl_OnMyEvent(object sender, MyEventArgs e)
{
    MyObject = new e.TypeYouNeedToCreate();  //TypeYouNeedToCreate implements IMyObject
}
(pseudo-code)
MyEventArgs : EventArgs
{
     public Type TypeYouNeedToCreate;
    ... this gets set appropriately on the constructor.
}
 
(on a page elsewhere in the application)
public IMyObject MyObject;
MyUserControl_OnMyEvent(object sender, MyEventArgs e)
{
    MyObject = new e.TypeYouNeedToCreate();  //TypeYouNeedToCreate implements IMyObject
}

Open in new window

hifisoftwareAsked:
Who is Participating?
 
patrickrivaConnect With a Mentor Commented:
You can use the following
Activator.CreateInstance(typeYouNeedToCreate);
 
If your constructor has parameters you need
 
 
Activator.CreateInstance(typeYouNeedToCreate, new object[] { blah, blah } );

Open in new window

0
 
AUmidhCommented:
I think you can declare this of System.Object Type.
[Reason] Since every type in .NET is derieved directly or indirectly from System.Object

Object MyObject = new e.TypeYouNeedToCreate();

and where ever you want to use it just parse like.

int intObject=(int)MyObject
0
All Courses

From novice to tech pro — start learning today.