C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Instead: Count returns the exact number of key-value pairs you have added (and have not removed).
First: This program adds 4 keys to the Dictionary. Its count at this point is equal to 4.
Next: One key is removed, resulting in a count of 3. The Dictionary is cleared, which puts its count at zero. The Count property is readonly.
ReadonlyC# program that counts keys in Dictionary
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
//
// Create new Dictionary with 4 keys.
//
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("carrot", 1);
dictionary.Add("pear", 4);
dictionary.Add("apple", 6);
dictionary.Add("kiwi", 3);
//
// Count the keys.
//
int count1 = dictionary.Count;
//
// Remove one key.
//
dictionary.Remove("pear");
//
// Count the keys again.
//
int count2 = dictionary.Count;
//
// Clear the Dictionary contents.
//
dictionary.Clear();
//
// Count the keys again.
//
int count3 = dictionary.Count;
//
// Write the counts of the Dictionary.
//
Console.WriteLine(count1);
Console.WriteLine(count2);
Console.WriteLine(count3);
}
}
Output
4
3
0
Note: You cannot easily access these members outside of the Visual Studio debugger. This could make performance analysis more difficult.
Also: The Count() extension, from the System.Linq namespace, likely has much worse performance.
CountNote: The "freeCount" field is subtracted from the "count" field, resulting in one "sub" IL instruction.
Implementation of Count: C#
public int Count
{
get
{
return (this.count - this.freeCount);
}
}