AminM
AminM

Reputation: 1824

The given key was not present in the dictionary. c#

i want to use Dictionary and Action to call some static method
here is my code:

public class  Works
{

    public static void DoWorkA()
    {
        Thread.Sleep(1000);
        Console.WriteLine("Doing Work A");
    }
    public static void DoWorkB()
    {
        Thread.Sleep(2000);
        Console.WriteLine("Doing Work B");
    }
    public static void DoWorkC()
    {
        Thread.Sleep(3000);
        Console.WriteLine("Doing Work C");
    }
}  

and this is is my main method

 try
        {
            var DoJob = new Dictionary<int, Action>();
            DoJob.Add(1, () => Works.DoWorkA());
            DoJob.Add(2, () => Works.DoWorkB());
            DoJob.Add(3, () => Works.DoWorkC());

            var input = Console.Read();
            var job = DoJob[input];
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);

        }
        Console.ReadKey();  

i use foreach to iterate keys and keys are exist

 foreach (var item in DoJob)
            {
                Console.WriteLine($"Item {item.Key} has Value {item.Value}");
            }  

Dictionary keys showed

but when i want to access key using input value i get exception

enter image description here

whats wrong?

Upvotes: 0

Views: 2481

Answers (2)

Shoonya
Shoonya

Reputation: 128

Console.Read() returns the int value of the next character from input stream, the value of character '1' is not 1, hence the exception.

https://msdn.microsoft.com/en-us/library/system.console.read(v=vs.110).aspx

You can convert the char to int using Convert.ToInt32(input) CharUnicodeInfo.GetDecimalDigitValue((char)input) as suggested in answer by Kevin https://stackoverflow.com/a/44735459/7970673

Upvotes: 1

Kevin Gosse
Kevin Gosse

Reputation: 39037

Console.Read returns a character code, not the actual value.

For instance, if you type "1", Console.Read will return 49.

You need some conversion to retrieve the desired value as an int:

var input = Console.Read();
var job = DoJob[CharUnicodeInfo.GetDecimalDigitValue((char)input)];    

Upvotes: 7

Related Questions