Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Instantiating an object whose type is not known until runtime?

Status
Not open for further replies.

keyser456

IS-IT--Management
Nov 21, 2003
73
US
public void AddItem()
{
this.Add(new ***); // here is where I'm stumped
}

private void Add(MySubItemType inSubItem)
{
this.Controls.Add(inSubItem);
}

There needs to be a type where the *** is but this type will not be known until runtime. Obviously, it will derive from MySubItem. Is there any way to do this other than passing in an instance of the unknown item type at runtime and somehow parsing the layout, then modifying the MySubItem on the fly? Something to the effect of:

this.Add(new typeof(SpecialSubItemType));

where SpecialSubItemType derives from MySubItemType

I know this doesn't work, but maybe it will help explain what I'm trying to do.
 
Hi,

I think what you're trying to do is instantiate various objects depending on the situation.

One way is to instantiate the object before you enter the AddItem method and pass it as an argument:
Code:
MySpecialObject obj = new MySpecialObject();

anobject.AddItem(obj);

...

public class AnObject
{

  public void AddItem(object obj)
  {
     if (obj is MySubItemType)
       this.Add(obj);
  }

  private void Add(MySubItemType inSubItem)
  {
      this.Controls.Add(inSubItem);
  }

Otherwise I fear you will have to wait until generics appear in .NET Framework 2.0.

Good Luck.



 
Thanks, but I think I found my answer. There is an activator class that allows you to create an instance of a type that you may not know until runtime.

MDSubformItem tempitem = (MDSubformItem)Activator.CreateInstance(this.subformitemType);

subformItemType is of System.Type and will be handed in after the program starts
 
faint -.-;;
i haven't catched the question for my poor eng.....

way to gold shines more than gold
 
keyser456 wants to do a late-binding call. The System.Activator is how you do it.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top