Dictionary Capacity

List(T) class has a handy Capacity property which tells you the length of the underlying collection used by it. However, there does not exist a counterpart of Capacity in Dictionary(TKey, TValue)Dictionary(TKey, TValue) backing field is an array of Dictionary(TKey, TValue) “entries” but its private.

Compiler won’t let you access the private property, but, you can access it using reflection as follows:

public static int Capacity<TKey, TValue>(this Dictionary<TKey, TValue> source)
    FieldInfo entriesField = source
        .GetField("entries", .NonPublic | BindingFlags.Instance);

    if (entriesField == null)
        return 0;
    var entries = entriesField.GetValue(source) as Array;
    if (entries != null)
        return entries.Length;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s