Reputation: 113
I am to c# and have been putting programs together through modification of existing code in visual studio. I am looking for some guidance to understand the difference between two ways of creating a list. both compile:
List <int> myList;
//versus
List <int> myList = new List <int>();
Upvotes: 1
Views: 120
Reputation: 9494
The first one List myList;
simply declares the variable, but the value is unassigned. The second one actually creates a new List object with no entries in it.
You should use the second option in most cases.
Upvotes: 3
Reputation: 23132
The first line doesn't create a List<int>
object. It only declares a variable named myList
that's of the type List<int>
. If you tried to do anything with that variable as is, the compiler would complain, because it's uninitialized.
The second line declares the variable and initializes it to a value: a new List<int>
object.
Upvotes: 0
Reputation: 11945
List <int> myList;
is the same as writing
List <int> myList = null; // aka it is not a list yet
Upvotes: 0
Reputation: 7154
The first line just creates a variable to hold a reference to a list.
The second one initializes the refrence with an empty list.
An attempt to call any method/access property on a reference without initializing it will end up in a null pointer exception
Upvotes: 1
Reputation: 161773
It's not subtle. One creates a list and one does not.
The first one simply declares a reference to a list. You would have to create the list later, before using it.
The second one declares a reference to a list and creates a list and sets the reference to refer to the new list, all at the same time.
Upvotes: 8