M
Matthew Wells
I am creating an array of a specific type. If I use Array.CreateInstance
and then try to assign as Object into an element I get
Error 2 Cannot apply indexing with [] to an expression of type
'System.Array'
Remember that I still can't cast becaue I don't know the type ahead of time.
You would think that the array is of type t becaust that's what it is
supposed to do. I believe that Array.CreateInstance is creating a generic
Array that can hold the type t, not creating an array of t types. I'm open
to suggestions.
and then try to assign as Object into an element I get
Error 2 Cannot apply indexing with [] to an expression of type
'System.Array'
Remember that I still can't cast becaue I don't know the type ahead of time.
You would think that the array is of type t becaust that's what it is
supposed to do. I believe that Array.CreateInstance is creating a generic
Array that can hold the type t, not creating an array of t types. I'm open
to suggestions.
Jon Skeet said:Matthew Wells said:I did say that's what I'm using (this is a little corrected from my last
post - I checked the actual line)
Object objList = Activator.CreateInstance(t, new Object[1] {5}); \\ for
five
elements
You'll notice that I'm now using the signature for CreatteInstance that
is
needed for an array of type t.
But you're still using *Activator*.CreateInstance rather than
*Array*.CreateInstance.
The call to Array.CreateInstance is simpler and more obviously
understandable, IMO.
But like I said before, if you use this, you can't assign a value to an
element of the array like:
objList[0] = 2;
You'll get an error. You have to declare another array, cast it, and
then
assign this array to that.
Object[] ObjListNew = (Object[])objList;
After you're done using ObjListNew, you can jsut refer to the original
objList since they refer to the same object.
Nice and neat.
All of that is still true with Array.CreateInstance, but you don't have
to go through as many hoops.