Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a good way to use Console.ReadKey for choosing between values without doing a lot of conversion between types?
    primarykey
    data
    text
    <p>Im using Console.ReadKey() to choose from a number of options that varies from time to time. Before this initial code snippet there is a for loop that counts occurances into counter variable of type int.</p> <p>The point is to use Console.ReadKey() to get an int.</p> <pre><code>int choice = ReadKey(); Console.WriteLine(""); if (choice &lt; counter) { mail.to = result[counter-1].email; } </code></pre> <p>By using the following methods</p> <pre><code>static int ReadKey() { ConsoleKeyInfo choice = Console.ReadKey(); char convertedchoice = choice.KeyChar; string convertedchoice2 = convertedchoice.ToString(); int result = TryInt(convertedchoice2); return result; } static int TryInt(string totry) { while (true) { int result; if (int.TryParse(totry, out result)) { return result; } Console.WriteLine("Sorry, you need to enter a number. Try again."); } } </code></pre> <p>I tried using ToString() but this was the way that it would let me do it in the end. So this looks kind of inneffective to me and hence I would really appreciate some guidance as what to do differently?</p> <p>Edit:</p> <p>I ended up with a combination of all the good answers below. Thanks alot guys.</p> <pre><code>static int ReadKey() { while (true) { ConsoleKeyInfo choice = Console.ReadKey(); if (char.IsDigit(choice.KeyChar)) { int answer = Convert.ToInt32(choice.KeyChar); return answer - 48; //-48 because 0 is represented in unicode by 48 and 1 by 49 etc etc } Console.WriteLine("\nSorry, you need to input a number"); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload