Creating array's dynamically

Bit of a simple one this, but I didn't know about it.

One of my favourite .NET tricks is using ArrayList.ToArray(Type objectType).  For those who don't know, this creates a strong array of objects for a given type.  So, if I chuck a load of objects into an ArrayList (say I'm doing some processing) and I want to pass the contents to some other method as an array, I use the ToArray(Type objectType) to get a strongly-types array, rather than a weak object[] array.

The helper function that ToArray(Type objectType) is using under the hood is Array.CreateInstance.  This version of CreateInstance (as opposed to System.Object.CreateInstance) returns a strong array of a given type and of a give size.  Pretty helpful.

1 Comment

  • Yes, that one rocks! It's really great for WebServices, since Arrays seem to work a bit better when returning your own objects. That way you can get the flexibility of the ArrayList for gathering data, then return a strongly typed array.



    Great tip, Matthew! (y)



    P.S. For all you VB.NET'ers out there that haven't yet discovered the pains of dynamic arrays (because of how they work under the covers), you'll want to take a look at this approach...again, thanks for pointing out that Method, Matthew!

Comments have been disabled for this content.