Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / C#

ArgumentOutOfRangeException e KeyNotFoundException: índice de lista ou chave de dicionário

Os parênteses retos dão acesso a uma lista por posição e a um dicionário por chave. Um índice inválido e uma chave em falta provocam exceções diferentes.

Versão: C# 12 and .NET 8; later runtimes may add compatible features

Sintaxe

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 um argumento está fora do intervalo permitido. O indexador de List<T> lança esta exceção ao ler ou escrever list[index] se index < 0 ou index >= list.Count. As posições começam em zero. Num array, pelo contrário, um acesso fora dos limites lança System.IndexOutOfRangeException.

Ler dictionary[key] num Dictionary<TKey, TValue> lança System.Collections.Generic.KeyNotFoundException se não existir uma chave correspondente. Mesmo uma chave do tipo int não representa uma posição. A atribuição dictionary[key] = value adiciona uma entrada se a chave não existir ou substitui o valor se já existir. Uma chave null provoca ArgumentNullException, não KeyNotFoundException.

Se o índice puder ser inválido, verifica 0 <= index && index < list.Count antes de aceder à lista. Se for normal que uma chave esteja em falta, usa TryGetValue(key, out var value). O método devolve true e fornece o valor guardado se encontrar a chave; caso contrário, devolve false e fornece default(TValue). Verifica o resultado booleano, não apenas o valor: o valor predefinido também pode estar guardado no dicionário. TryGetValue também rejeita uma chave null, lançando ArgumentNullException.

Exemplos

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` está fora dos limites da lista com um único elemento e não existe como chave no dicionário. São os próprios indexadores que lançam as exceções; os blocos `catch` apenas apresentam os nomes dos tipos. `TryGetValue` trata a ausência da mesma chave sem lançar uma exceção.

Lições relacionadas

  • C# · Lição 7 · Intermédio · Versão: 2

Fontes