0

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?

AminM
  • 1,658
  • 4
  • 32
  • 48

2 Answers2

7

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)];    
Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94
1

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

Shoonya
  • 118
  • 8
  • What you're thinking of would be a compile error. What you're suggesting doesn't fix the issue, the char `'1'` converts to the int `49`: http://ideone.com/SpWNqA – CodeCaster Jun 24 '17 at 11:06
  • yes, my bad. The fix I suggested earlier wouldn't have worked. Hence updated my answer – Shoonya Jun 26 '17 at 18:00