Search code examples
c#variablesconsole.writelineconsole.readkey

Why can't you put Console.ReadKey() in front of the text displayed to the console, or assign Console.ReadKey() to a variable?


using System;

class MainClass {
  public static void Main (string[] args) {
    Console.WriteLine("Press any key to continue...");
    Console.WriteLine(" key pressed", Console.ReadKey());
  }
}

this code works and has no errors but

using System;

class MainClass {
  public static void Main (string[] args) {
    Console.WriteLine("Press any key to continue...");
    Console.WriteLine(Console.ReadKey(), " key pressed");
  }
}

This doesn't work and I get an error

Error CS1502: the best overload method match for 'System.Console.WriteLine(string, object)' has some invalid arguments

and

Error CS1503: Argument '#1' cannot convert 'System.ConsoleKeyInfo' expression to type 'string'

I'm new to C# so I don't know much about the language (only ever used Python before), but in Python, I would write this code as

keyPressed = input("Type a key(s) ")
print(keyPressed, "is the key(s) you pressed")

I also can't just assign ReadKey() to a variable

var keyPressed = Console.ReadKey();
Console.WriteLine("the key you pressed was {0}", keyPressed);

For the block of code above, I want to have whatever key the user presses stored inside the variable keyPressed, but it doesn't work.

My question is why can't you put Console.ReadKey() in front of the text I want displayed on the console, or assign Console.ReadKey() to a variable, and how would you have whatever key the user presses assigned to a variable?


Solution

  • You are using the method Console.WriteLine(), which have a lot of overloads like :

    • Console.WriteLine(String)
    • Console.WriteLine(Int64)
    • Console.WriteLine(String, Object)

    So on and so on. But there is no overload :

    • Console.WriteLine(Object, String)

    And the latter is the one you are trying to use when doing Console.WriteLine(Console.ReadKey(), " key pressed");

    Your Console.ReadKey() return a ConsoleKeyInfo not a String which does not derive from String or any other objects you can find in the overloads. So since it doesn't exist it cannot work and you get the error you have mentioned.

    Usually you can use autocompletion to find out what are the overloads of a method or check the documentation which is mostly the best way to find and understand things.

    Hope this helps.