Sure! In C#, you can get user input from the console using the Console.ReadLine()
method. This method reads a line of characters from the console and returns it as a string. Here's how you can do it with an example:
Example
using System;
class Program
{
static void Main()
{
// Prompt the user to enter their name
Console.WriteLine("Please enter your name:");
// Read the user input from the console
string name = Console.ReadLine();
// Greet the user with the entered name
Console.WriteLine("Hello, " + name + "! Welcome to the program.");
}
}
Explanation:
Console.WriteLine()
to display a prompt asking the user to enter their name.Console.ReadLine()
to read the user's input from the console. Whatever the user types until they press Enter will be stored as a string in the variable name
.Console.WriteLine()
again to greet the user with the entered name.When you run this program, it will display the prompt asking for the user's name. After the user enters their name and presses Enter, the program will greet them with the entered name.
For example:
Please enter your name:
[User enters their name, e.g., "John"]
Hello, John! Welcome to the program.
This demonstrates how to get user input from the console in C# and use it in your program.