とあるコードのデバッグ中に「お、落ちそうだな。ココ。」と思い検証。
問題なかった。知らなかったなあ。
調べたら公式ドキュメントに書いてあった。
[Dictionary_TKey,TValue_.Item[TKey] Property]
(https://docs.microsoft.com/ja-jp/dotnet/api/system.collections.generic.dictionary-2.item?view=netframework-4.8)
プロパティ値
TValue
指定されたキーに関連付けられている値。指定したキーが見つからなかった場合、get 操作は KeyNotFoundException をスローし、set 操作は指定したキーを持つ新しい要素を作成します。
以下の4パターンを検証(検証 by このサイト)
・存在するキーを指定し、値を取得
・存在しないキーを指定し、値を取得
・存在するキーを指定し、値を設定
・存在しないキーを指定し、値を設定
var dict = new Dictionary<int, int>();
dict.Add(0, 100);
// 正常ケース
// 存在するキーを指定し、値を取得
try
{
var a = dict[0];
Console.WriteLine($"success - value is {a}");
}
catch
{
Console.WriteLine("failure - key not found");
}
> success - value is 100
// 異常ケース
// 存在しないキーを指定し、値を取得
try
{
var a = dict[1];
Console.WriteLine($"success - value is {a}");
}
catch
{
Console.WriteLine("failure - key not found");
}
> failure - key not found
// 正常ケース
// 存在するキーを指定し、値を設定
try
{
dict[0] = 200;
var a = dict[0];
Console.WriteLine($"success - value is {a}");
}
catch
{
Console.WriteLine("failure - key not found");
}
> success - value is 200
// 正常ケース?
// 存在しないキーを指定し、値を設定
try
{
dict[1] = 300;
var a = dict[1];
// 問題なく動く
Console.WriteLine($"success - value is {a}");
}
catch
{
Console.WriteLine("failure - key not found");
}
> success - value is 300