Start learning free

LESSON 107 OF 674 · ARRAYS I

List Size in C#

Lesson

We can get the size of an List using the .Count property:

List<int> ourArray = new List<int>(new[] {50, 40, 30});

// Printing the size:
Console.WriteLine(ourArray.Count); // Output: 3

// Changing the List:
ourArray.RemoveAt(2);

// Printing the new size:
Console.WriteLine(ourArray.Count); // Output: 2

Using the size

We can use the size to access items from the end of a List.

Because lists are 0-indexed, the index of the last item is size - 1:

List<int> ourArray = new List<int>(new[] {50, 40, 30});

int size = ourArray.Count;

// Printing the last item:
Console.WriteLine(ourArray[size - 1]); // Output: 30

// Printing the second to last item:
Console.WriteLine(ourArray[size - 2]); // Output: 40

Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check