I’m new to C# but have a strong background in ActionScript 3.
In AS3, you can define an array like so:
var array:Array = [];
And then add unlimited items to that array via push():
array.push(1);
I’ve noticed in C# that you need to define a permanent (I think) length for an array, eg:
string[] array = {"this","has","a","length","of","six"};
Or:
string[] array = new string[6];
If I try add new items to the array that will fall outside of the length of this array, I’ll get an error:
array[6] = "failure";
I’m finding it hard to go from being able to add/remove items from an array freely, to now having to define a maximum length.
I’m not really sure how this should be approached in a game environment when an array could contain anywhere between 0 and 10000 entities.
- Do I just make the array length really long to cater for all the realistic amounts of entities I could have?
- Is there a different way I should store my entities that should be used in C# that I don’t know of?
- Do I write my own class that redeclares the array with a new length and copies the objects from the old array into the new, with 1 free slot left over?
Any suggestions would be helpful!
Arrays are of fixed size in C# as you have found out; Resizing an array references a new array instance of the specified size and copies the items in the array into the newly referenced instance.
What you are looking for in .NET are the generic collections such as
List<T>, whereTis a generic type parameter for some type. In the particular case you have highlighted, you would want to use aList<string>now you can add strings to the collection using
Add()In C#3, collection intializers were introduced so that you can initialize a collection much more succinctly
When you create an instance of a generic collection, it starts with a default size; the default size for
List<T>in .NET 4 is 0, although this is increased to 4 when the first item is added (default sizes may vary across different collection types and framework versions, so it sounds like default size is an implementation detail). Collections are generally resized by the framework using a doubling strategy, that is, when the collection has reached capacity and another item is trying to be added, the collection capacity is usually doubled – this is taken care of in the implementation of the generic collections and something you don’t need to be concerned with.When you may want to bear it in mind is when you are adding a known quantity of items to a collection or know an order of magnitude of how many items you’re going to add. In this case, you may consider using the overloaded constructor of
List<T>that takes anintfor a default size