How to use dictionary indexer in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, int> dictionary = new Dictionary<int, int>();

            dictionary[1] = 178;
            dictionary[2] = 9813;

            Console.WriteLine(dictionary[1]);
            Console.WriteLine(dictionary[2]);
            Console.WriteLine(dictionary[3]); // exception - element not exists
        }
    }
}

/*
run:

178
9813

Unhandled Exception: System.Collections.Generic.KeyNotFoundException: The given
key was not present in the dictionary.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at ConsoleApplication_C_Sharp.Program.Main(String[] args) in d:\Conso
leApplication_C_Sharp\ConsoleApplication_C_Sharp\Program.cs:line 17

*/

 



answered Jan 5, 2017 by avibootz

Related questions

1 answer 117 views
1 answer 118 views
118 views asked Apr 27, 2017 by avibootz
1 answer 119 views
119 views asked Jan 15, 2017 by avibootz
1 answer 130 views
1 answer 91 views
91 views asked Nov 26, 2020 by avibootz
6 answers 420 views
420 views asked Sep 5, 2019 by avibootz
1 answer 119 views
...