简体   繁体   中英

Good Practice? Redefining Arrays to Change their Size

I'm working in Unity in C#, but this is a more general programming practice question.

dataType[] array = new dataType[x];

//Further down
dataType[] newArray = new dataType[array.Length + 1];

for (int i=0;i<array.Length;i++){
    newArray[i] = array[i];
}

Is this considered bad practice? Is it more/less efficient than just using an ArrayList? I'm only performing this operation at the beginning of a level and then never again, so is it worth just working with ArrayLists?

You should use dynamic data structures when you do not know the exact size of an array. List is a better option if you compare with ArrayList. ArrayList works only on objects whereas List<> make use of generics (which works on specific type or on object as well). This will help you create high performing and maintainable code.

Yes, this is bad practice. If you expect your array size to change then use a List instead of an Array. List works just like an array in terms of indexing. To add new items to the List use Add(). You can even call ToArray() on the list to get an Array from it.

http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

If you come across a situation where you can't use a List and need to grow your Array, use Array.Resize() as shown below.

int[] array = new int[5];

Console.WriteLine(array.Length);

Array.Resize<int>(ref array, 20);

Console.WriteLine(array.Length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM