How to use dictionary in class with C#

1 Answer

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

namespace ConsoleApplication_C_Sharp
{
    class Test
    {
        Dictionary<string, int> dictionary = new Dictionary<string, int>()
        {
            {"c#", 1},
            {"java", 2},
            {"c++", 3}
        };
        public int GetValue(string s)
        {
            return dictionary[s]; 
        }
        public void AddKeyValue(string key, int value)
        {
            dictionary.Add(key, value);
        }
        public void Show()
        {
            foreach (KeyValuePair<string, int> keyval in dictionary)
            {
                Console.WriteLine("Key = {0} - Value = {1}", keyval.Key, keyval.Value);
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();

            Console.WriteLine(t.GetValue("c#"));

            t.AddKeyValue("c", 4);

            t.Show();
        }
    }
}

/*
run:

1
Key = c# - Value = 1
Key = java - Value = 2
Key = c++ - Value = 3
Key = c - Value = 4

*/

 



answered Jan 5, 2017 by avibootz

Related questions

1 answer 253 views
1 answer 224 views
224 views asked Jun 21, 2024 by avibootz
1 answer 299 views
1 answer 246 views
1 answer 260 views
1 answer 255 views
2 answers 393 views
393 views asked Aug 4, 2018 by avibootz
...