Start learning free

LESSON 127 OF 674 · DICTIONARIES

Dictionary Length in C#

Lesson

In C#, you can get the number of key-value pairs in a Dictionary using its Count property:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores["Alice"] = 95;
scores["Bob"] = 87;
scores["Charlie"] = 72;

int count = scores.Count;
Console.WriteLine(count);  // 3

Count is a property, not a method, so it takes no parentheses. It gives the number of entries. You can also check if a dictionary is empty by comparing it with 0:

Console.WriteLine(scores.Count == 0);  // False
Dictionary<string, int> empty = new Dictionary<string, int>();
Console.WriteLine(empty.Count);        // 0

Assignment
Follow the Coding Tutorial and get the number of entries in scores!


Hint
Use scores.Count and assign it to count.

STEP 1 OF 1
    Ctrl + Enter to check