Input and output operations are fundamental in C# programming. They allow your program to interact with users and handle data efficiently. This guide explores essential I/O concepts in C#.
C# provides simple methods for reading user input from the console. The most common method is Console.ReadLine()
.
string userInput = Console.ReadLine();
This method reads a line of text from the console and returns it as a string. For numeric input, you'll need to parse the string:
int number = int.Parse(Console.ReadLine());
To display information to the user, C# offers several methods. The most versatile is Console.WriteLine()
.
Console.WriteLine("Hello, World!");
int age = 25;
Console.WriteLine($"I am {age} years old.");
For output without a new line, use Console.Write()
:
Console.Write("Enter your name: ");
string name = Console.ReadLine();
C# provides robust file I/O capabilities through the System.IO
namespace. Here's a basic example of writing to a file:
using System.IO;
string content = "Hello, File!";
File.WriteAllText("output.txt", content);
Reading from a file is equally straightforward:
string fileContent = File.ReadAllText("input.txt");
Console.WriteLine(fileContent);
As you progress, explore more advanced I/O topics like:
Mastering input and output operations is crucial for creating interactive and data-driven C# applications. Practice these concepts to enhance your programming skills and build more sophisticated programs.