Programs are much more engaging when they are interactive. In C#, you can accept input from the user via the console using the Console.ReadLine() method.
The Console.ReadLine() method pauses program execution and waits for the user to type something and press the Enter key. It then returns the typed input as a string.
using System;class Program { static void Main() { // Prompt the user Console.WriteLine("Enter your username:"); // Read the user input and store it in a variable string userName = Console.ReadLine(); // Print out a personalized greeting Console.WriteLine("Hello, " + userName + "!"); } }
Because Console.ReadLine() always returns a string, you cannot directly assign user input to an integer variable (like int). If you try, C# will throw an error.
To get a number from a user, you must use type conversion methods provided by the Convert class, such as Convert.ToInt32() for integers.
using System;class Program { static void Main() { Console.WriteLine("Enter your age:"); // Read the input (string), then convert it to an int int age = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("You are " + age + " years old."); } }
Warning: If the user types text (like "twenty") instead of a number (like "20"), Convert.ToInt32() will cause the program to crash. Handling these errors is an advanced topic called Exception Handling.
What data type does Console.ReadLine() ALWAYS return?