Resize my Array!

You don’t use arrays do you? You’re using generic classes like List because of type safety, right? Good, me too.

Except, I AM using arrays. I’ve generated some classes from an XML schema file using xsd.exe and guess what... it puts child elements (or rather classes created from child elements) into arrays under parent elements. So for an xml document like this:

<Author name="Iain M. Banks">
<Book title="Excession"/>
<Book title="Look To Windward"/>
</Author>


You get an Author class that exposes a Book property, which is an array of AuthorBook objects.

Which is great when you deserialize a document, but what if you want to add a new book? Reaching back into your dusty knowledge of C#, how do you extend an array?
Author.Book.Add()
– nope you’re thinking of a generic List or some other useful collection. Arrays are immutable – they need dimensioning up front, so it looks like we’re in for some hokey For loop to iterate the current array and place the contents into a new one, ugh...

Except we’re not. In .Net 2.0 Array.Resize() came to the rescue. You can simply do this:

AuthorBook myBooks = author.Book;
Array.Resize(ref myBooks, author.Book.Length + 1);
author.Book[author.Book.Length - 1] = new AuthorBook("The Player Of Games");


OK, so under the hood there’s probably a For loop – but at least I haven’t had to do it in my code. So now you know – except, of course, you don’t use arrays, do you?

Comments