While @Galaxy-1-Studios in general already answers it, i’d like to expand it a bit:
When you only write:
List<int> number;
number.add(1);
this will throw an error. A NullreferenceException
. Reason for this is, that the variable number
has no value assigned. It is null
.
In general you can divide types of variables into 2 groups: value-Types and reference-types.
A value type is something like: bool, int, float, double …
A reference type is always an Object
which when created will always be null
If we create a value type variable it automatically get’s assigned its default
value. (In case of numbers i think always 0).
int i;
Debug.Log(i); //should print "0"
if we create a reference type variable like a List:
List<int> numbers;
Debug.Log(numbers); //should print "null"
So here we see, we actually have to create an object for any reference type:
List<int> numbers;
numbers = new List<int>(); //actually fill the variable "numbers" with a new object
numbers.add(1); //now this works
Now the question “why do i have to write new List<int>()
once more” is actually a good one: Do we really have to?
List<int> numbers = default; //this works and should create the `default` for the given variable type
using default
can be a thing here to shorten this if you want, but imo it is sometimes good to write it twice, helps to find errors.
Apart from that there is one reason where specifying this is important. Consider the following class structure:
class BaseClass {}
class SubClass : BaseClass {}
Now i can create a variable of type BaseClass
but can fill in values of both classes:
BaseClass someVar;
someVar = new SubClass(); //create new SubClass object
someVar = new BaseClass(); //create new BaseClass object
both lines will work and when using inheritance properly this is a crucial part to understand. Thus you can see that there are some cases where it actually is important to explicitly write the new List<int>()
as to specify what you actually want to have in your variable.
Those were a lot of words, hope it is clear and not confusing.