Input and output (I/O) operations are an essential part of any programming language, and C# is no exception. In this article, we will explore the basics of input and output in C#.
Read Also- Multithreading in C#
Console Input in C#
The Console class in C# provides methods for reading input from the console. The most common method for reading input is the ReadLine method, which reads a line of text input by the user.
To use the ReadLine method, we first need to create an instance of the Console class. We can then use the ReadLine method to read input from the user. Here’s an example:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");
}
}
In this example, we first use the WriteLine method to print a prompt to the console, asking the user to enter their name. We then use the ReadLine method to read the user’s input and store it in a variable called “name”. Finally, we use the WriteLine method again to print a greeting to the console, addressing the user by name.
Console Output in C#
The Console class also provides methods for outputting text to the console. The most common method for outputting text is the WriteLine method, which writes a line of text to the console and adds a newline character at the end.
Here’s an example:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
}
}
In this example, we use the WriteLine method to output the text “Hello, world!” to the console. The output will be followed by a newline character, so the next line of output will begin on a new line.
Conclusion
Input and output are important concepts in C# programming. By using the Console class, we can read input from the user and output text to the console. These basic I/O operations are essential for creating interactive console applications in C#