Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

ArgumentOutOfRangeException and KeyNotFoundException: list index vs. dictionary key

Square brackets access a list by position and a dictionary by key. An invalid list index and a missing dictionary key raise different exceptions.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

List<T>: T this[int index] { get; set; } — list[index]
Dictionary<TKey, TValue>: TValue this[TKey key] { get; set; } — dictionary[key]
Dictionary<TKey, TValue>: bool TryGetValue(TKey key, out TValue value)

System.ArgumentOutOfRangeException means an argument is outside its allowed range. The List<T> indexer throws it when reading or writing list[index] if index < 0 or index >= list.Count. Positions start at zero. Do not confuse this with array access: indexing outside an array's bounds throws System.IndexOutOfRangeException.

Reading dictionary[key] from a Dictionary<TKey, TValue> throws System.Collections.Generic.KeyNotFoundException if no matching key exists. Even an int key is not a position. Assigning dictionary[key] = value adds an entry for a missing key or replaces the value for an existing key. A null key causes ArgumentNullException, not KeyNotFoundException.

If an index might be invalid, check 0 <= index && index < list.Count before accessing the list. If a missing key is expected, use TryGetValue(key, out var value). It returns true and the stored value for a match, or false and default(TValue) for a missing key. Check the Boolean result, not the value alone: the default value can itself be stored in the dictionary. TryGetValue also rejects a null key with ArgumentNullException.

Examples

using System;
using System.Collections.Generic;

var list = new List<int> { 0 };
var dictionary = new Dictionary<int, int> { [0] = 0 };
int indexOrKey = 1;

try
{
    _ = list[indexOrKey];
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine($"List: {ex.GetType().Name}");
}

try
{
    _ = dictionary[indexOrKey];
}
catch (KeyNotFoundException ex)
{
    Console.WriteLine($"Dictionary: {ex.GetType().Name}");
}

if (!dictionary.TryGetValue(indexOrKey, out _))
{
    Console.WriteLine("TryGetValue: key not found");
}

Result

List: ArgumentOutOfRangeException
Dictionary: KeyNotFoundException
TryGetValue: key not found

`1` is outside the bounds of the one-element list and is absent as a dictionary key. The indexers themselves throw; the `catch` blocks only print the type names. `TryGetValue` handles the same missing key without throwing.

Related lessons

  • C# · Lesson 7 · Intermediate · Version: 2

Sources