I got it. The problem was in the type declaration. I also had to use
the .GetConstructor method. The type with an array is idfferent thatn
Type t = Type.GetType(stype) + "[]");
object objList = t.GetContructor(new Type[](typeof(int32))).invoke(new
Object[] (...element count...));
You can't assign to objList[0], but you can create a new object{]
objListNew and cast it to an array of objects. Then I can still assign
objList to the main entity's property that is expecting an array of type
t.
I'm reading metadata I've netered into an Access table that defines
objects.
Each object can have primitive property types like string, int, etc,
but can
also have other objects defined as properties.. Here is one brief
example.
Customer (entity)
FirstName
LastName
Address (entity)
Contacts[] (entity) - this is an array of contacts.
Contact (entity)
Address (entity)
I'm transferring data from one system to another. I have a recursive
function set up to read from the (in this case the customer table)
create an
instance of the object, assign values to the properties, then create
the
array and assign subentities to that and then assign the array to the
parent
entity's property. The theory works fine. As I said, all the data is
being
read from a table so I have no way of knowing what entities are needed
ahead
of time. This works when I only need one instance of an entity (like
the
Customer's Address entity) using
string sEntityName = "Contact"
Type t = Type.GetType(sEntityName);
Object = objNew = Activator.CreateInstance(t);
I've tried your suggestions of using an ArrayList and
Array.CreateInstance.
These work so I can assign objects into them, but when it comes time
to add
the array or list to the Customer entity, it fails because the
Custoemr
entity is expecting an array of Contacts, not a generic Array or
ArrayList.
I can't cast either because casting requires a known type. I've tried
(t.GetType()) and (typeof(t)) without success.
The way that the arrays are created with Jason's original code creates
the right type of array at runtime. Presumably you're using reflection
to set the property anyway, so it should be fine.
Could you post a short but complete program which demonstrates the
problem?
See
http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.