A big limitation of static arrays in C# is the fact that once the array is created, it has a fixed size.
The List overcomes this limitation by having variable size and allowing for elements to be added or removed.
Creation:
We create a List by using the keywords new and List, then writing the type of the elements inside <> followed by parentheses:
new List<string>();
This code creates an empty List where each item is a string.
Declaring a variable:
To use the list later, store it in a variable whose type is List with the type of the elements, like this:
List<string> sandwich = new List<string>();
Initialization:
You can also initialize a List at creation by writing the entries in curly braces after the constructor, with a comma between each entry, like this:
List<string> sandwich = new List<string> {
"peanut butter", "jelly", "bread"
};
We created a List named sandwich which consists of 3 items: "peanut butter", "jelly" and "bread".
Assignment
Follow the Coding Tutorial and let's create some Lists!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
