CKTIS / C#
ArgumentOutOfRangeException y KeyNotFoundException: índice de lista o clave de diccionario
Los corchetes permiten acceder a una lista por posición y a un diccionario por clave. Un índice no válido y una clave ausente provocan excepciones distintas.
Versión: C# 12 and .NET 8; later runtimes may add compatible features
Sintaxis
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 indica que un argumento está fuera del intervalo permitido. El indizador de List<T> la produce al leer o escribir list[index] si index < 0 o index >= list.Count. Las posiciones empiezan en cero. En cambio, acceder a una posición fuera de los límites de un array produce System.IndexOutOfRangeException.
Leer dictionary[key] en un Dictionary<TKey, TValue> produce System.Collections.Generic.KeyNotFoundException si no hay una clave que coincida. Una clave de tipo int tampoco es una posición. La asignación dictionary[key] = value añade una entrada si la clave no existe o sustituye el valor si ya existe. Una clave null produce ArgumentNullException, no KeyNotFoundException.
Si el índice puede ser incorrecto, comprueba 0 <= index && index < list.Count antes de acceder a la lista. Si es normal que falte una clave, usa TryGetValue(key, out var value). El método devuelve true y entrega el valor almacenado si encuentra la clave; si no, devuelve false y entrega default(TValue). Comprueba el resultado booleano, no solo el valor: el diccionario también puede almacenar el valor predeterminado. TryGetValue también rechaza una clave null con ArgumentNullException.
Ejemplos
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");
}Resultado
List: ArgumentOutOfRangeException Dictionary: KeyNotFoundException TryGetValue: key not found
`1` queda fuera de los límites de la lista de un solo elemento y no está presente como clave del diccionario. Los propios indizadores producen las excepciones; los bloques `catch` solo muestran los nombres de los tipos. `TryGetValue` maneja la ausencia de esa misma clave sin producir una excepción.
Lecciones relacionadas
- C# · Lección 7 · Intermedio · Versión: 2