Search code examples
c#castinginttype-conversionreadkey

C# Conversion of ReadKey() to int


I am new to C# and was told to create a Text-based Pokemon Battle Simulator, so in the code below, I have a method to get the user input and decide which nature the Pokemon get :

public static void NatureSelection(out int statIndex1, out int statIndex2)
    {
        Console.WriteLine("If you wish to have a neutral nature, Enter 0 in the next line, If not, enter any key to continue");
        char holder = Convert.ToChar(Console.ReadKey());
        statIndex1 = Convert.ToInt16(holder);
        if (statIndex1 == 0) 
        {
            statIndex2 = 0;
        }

        Console.WriteLine("Please Select A Nature For Your Pokemon By Entering The Number Beside The Stats That You Want To Increase ");
        statIndex1 = Convert.ToInt16(Console.ReadKey());
        while (!(statIndex1 > 0 && statIndex1 <=5))
        {
            statIndex1 = Convert.ToInt32(Console.ReadKey());
            Console.WriteLine("Invalid Value,Please Try Again");
        }


        Console.WriteLine("Now Enter The Number Beside The Stats That You Want To Decrease ");
        statIndex2 = Convert.ToInt32(Console.ReadKey());
        while (!(statIndex2 > 0 && statIndex2 <= 5))
        {
            statIndex2 = Convert.ToInt16(Console.ReadKey());
            Console.WriteLine("Invalid Value,Please Try Again");
        }

    }

However when I try to convert the readkey to int, it gives an error that says:

this line gives the errror:

char holder = Convert.ToChar(Console.ReadKey());

An unhandled exception of type 'System.InvalidCastException' occurred in mscorlib.dll

Additional information: Unable to cast object of type 'System.ConsoleKeyInfo' to type 'System.IConvertible'.

Can someone explain what this mean and how I can fix it ?


Solution

  • Definitely this line Convert.ToInt16(Console.ReadKey()) cause the exception, because of a failure conversion, I suggest you to use like this:

      int myNumber = (int)(Console.ReadKey().KeyChar);
    

    Since Console.ReadKey() returns a ConsoleKeyInfo So that .KeyChar will give you the corresponding character value, which can easily be converted to an integer using implicit conversion. But this will give ascii values for characters as well.

    Another option for you is TryParse, so that you can identify the conversion result also. that is the code will be like this:

    int myNumber;
    if (!int.TryParse(Console.ReadKey().ToString(), out myNumber))
    {
        Console.WriteLine("Conversion faild");
    }
    // myNumber holds the result