How To Create And Use Lists In C#

In order to create a list, you must utilize the “Namespace” in the example below.

This namespace will open up the C# library to allow for the use of lists in your code.

A list is very similar to an array however a list is dynamic and allows for items to be added to it or removed from it during runtime. An array is a fixed-length/size which determines the max number of elements that it is capable of holding.

You must declare the list's “Type” which determines what the list can store. In this example, I used the type “GameObject” as I am wanting to keep a list of all the items in my inventory.

Then you must give the list a name. Since my list is going to track the player’s stored items, I named the list “items”.

That’s it; the list is made! Now let’s look at how to use the list.

Using this line of code, you can add your game objects to the list. Just replace where it says “GameObject” with the specified object that you are wanting to add.

Using this line of code, you can remove your game objects from the list. Just replace where it says “GameObject” with the specified object that you are wanting to remove.

With this line, you can clear the list entirely.

You can also call on specific items in the list similar to how you would with an array.

And even check the count of how many items are in your list!

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store