Domanda

Here's my original code, which I was trying to modify to limit data entry to a single char, converted to uppercase.

    public char promptForGuess()
    {
        Console.Write("\nGuess a letter: ");
        return Convert.ToChar(Console.ReadLine().ToUpper());
    }

I thought it would be easy:

    public char promptForGuess()
    {
        Console.Write("\nGuess a letter: ");
        return Convert.ToChar(Console.ReadKey().ToUpper());
    }

but I get this error:

'System.ConsoleKeyInfo' does not contain a definition for 'ToUpper' and no extension method 'ToUpper' accepting a first argument of type 'System.ConsoleKeyInfo' could be found (are you missing a using directive or an assembly reference?)

which doesn't really mean a lot to me...and google wasn't terribly helpful either. I tried this,

    public char promptForGuess()
    {
        Console.Write("\nGuess a letter: ");
        return = Console.ReadKey();
    }

and got a message the I can't implicitly convert ReadKey() to char.

    public String promptForGuess()
    {
        Console.Write("\nGuess a letter: ");
        return Console.ReadKey();
    }

tells me that I can't implicitly convert Console.ReadKey() to String

So if it's not char and not String, what type is Console.ReadKey(). And how can I return a char with ToUpper()?

È stato utile?

Soluzione

Console.ReadKey() returns a ConsoleKeyInfo. In the future you can answer these questions yourself by reading the documentation. The page for ConsoleKeyInfo has a complete example of how to use it. The key bit is:

cki = Console.ReadKey();
Console.WriteLine(cki.Key.ToString());
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top