Austin
Austin

Reputation: 109

Best structure for a growing collection of objects in C#?

For my Game Programming class, I am designing a class for a player character. The player can collect power-ups throughout the game, which are held onto and can be used whenever the player chooses.

I thought a dynamic array would work well, but my background is in C++ (we are using Unity in class, which uses Java & C#), and I know that memory deallocation is handled differently in C# (I know there is a garbage collector, but don't really know much about how it functions). After looking around the web a while, I couldn't find anything that seemed to fit the functionality I need (or if I did it was over my head and I didn't realize it).

If someone can list a C# structure, or structures, that would be good for storing a growing collection of objects, it would be extremely helpful.

Upvotes: 4

Views: 2194

Answers (2)

Paul Sasik
Paul Sasik

Reputation: 81479

Start by looking at .NET's generic collections. (.NET generics are similar in concept to C++ templates.) Either List or Dictionary will likely be useful to you depending on how you need to store and retrieve your objects.

Since you'll probably have types of objects you may consider using a Dictionary of Lists where the key will be a string identifier or an enumeration of types of collected objects and the value will be a list of object instances.

Upvotes: 0

Sam Holder
Sam Holder

Reputation: 32936

List is probably the simplest structure you could use, it is like a dynamic array which will automatically grow as you add things to it. It is strongly typed so it will only contain objects of the same type (if you have some interface for your power-ups you can have a list of IPowerUp instances)

Upvotes: 2

Related Questions