Add a new instance to an array with late binding - dynamic

G

garak

Hi,

I want to add one element to an Array dynamicly, according to the type
of the parameter ALLDATA.
ALLDATA may be of type PObjects, PActions, PMaterials.
I Thougth about my code to look something like this:

public void GetAllData (Object[] AllData) {
Type dataType = AllData.GetType();
AllData[curData] = new dataType();
}

But the compiler says :
error CS0246: The type or namespace name 'dataType' could not be
found.


One more problem is, that AllData.GetType returns PObjects[] etc. when
I need PObjects.

Can someone help me please.

Thank you very much.
Frank
 
J

Jon Skeet [C# MVP]

garak said:
I want to add one element to an Array dynamicly, according to the type
of the parameter ALLDATA.
ALLDATA may be of type PObjects, PActions, PMaterials.
I Thougth about my code to look something like this:

public void GetAllData (Object[] AllData) {
Type dataType = AllData.GetType();
AllData[curData] = new dataType();
}

But the compiler says :
error CS0246: The type or namespace name 'dataType' could not be
found.

You need to use Activator.CreateInstance, or get a constructor from the
Type and invoke it.
One more problem is, that AllData.GetType returns PObjects[] etc. when
I need PObjects.

See Type.GetElementType()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top