LoginSignup
1
0

More than 3 years have passed since last update.

【C#】Dictionaryは存在しないキーを指定して値を設定できる

Last updated at Posted at 2019-09-12

とあるコードのデバッグ中に「お、落ちそうだな。ココ。」と思い検証。
問題なかった。知らなかったなあ。

調べたら公式ドキュメントに書いてあった。
Dictionary_TKey,TValue_.Item[TKey] Property

プロパティ値
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
1
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0