How to create and use List in Unity using C#

How to create and use List in Unity using CSharp

· 1 min read

List is basically ArrayList but with the two following features:

  • Type safe
  • Can only store same type of data
  • Inconsistent memory address
using System.Collections.Generic;

List<string> weapons = new List<string> ();
weapons.Add("gun");
weapons.Add("knife");
weapons.Add("bomb");

// also we can just use the var 
var anotherList = new List<string> ();

// var with some init values
var anotherList = new List<string> () {
	"BMW", "Audi", "Lexus"
};

// remove one element
anotherList.Remove("BMW");    // anotherList: "Audi", "Lexus"

// remove all elements
anotherList.Clear();

// remove all the matched elements
anotherList.RemoveAll(name => name == "Audi"); // anotherList: "BMW", "Lexus"