Array.Resize warning

The .NET Framework 2.0 addition of Array.Resize as a generic method is a big plus.  One of the really nice things about it is that if the array passed to it is a null reference, it creates a new array.  That makes a call like this seem natural:

MyArrayType[] MyArray;
Array.Resize<MyArrayType>(ref MyArray, MyArray.Length + 1);

However, you’ll get a null reference exception if you do that and the array is null.  Here’s how to make the call safely:

Array.Resize<MyArrayType>(ref MyArray, (null == MyArray) ? 1 : MyArray.Length + 1);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s