For every (console) program C# provides the standard POSIX streams for
input and output, connecting your program to the console. These streams
are readily available through the System.Console
class.
System.Console.Out
represents the standard output stream, typically directed to the console. The System.Console.WriteLine()
method is commonly used to write data to the console.
public class Example { public static void Main(string[] args) { System.Console.WriteLine("Hello, world!"); // Output to the console int age = 30; System.Console.WriteLine("My age is " + age + "."); // String concatenation System.Console.WriteLine($"My age is {age}."); // String interpolation (C# 6+) System.Console.Out.WriteLine("Another way to write."); // Less common, but equivalent. } }
String interpolation (using $""
) is a cleaner way to embed variables directly in strings (C# 6 and later). String concatenation (using +
) is also valid.
System.Console.In
represents the standard input stream, typically connected to the keyboard. The System.Console.ReadLine()
method reads a line of text from the console.
public class Example { public static void Main(string[] args) { System.Console.Write("Enter your name: "); // Write without a newline string name = System.Console.ReadLine(); // Read a line System.Console.Write("Enter your age: "); string ageString = System.Console.ReadLine(); int age = int.Parse(ageString); // Convert string to integer (error handling omitted for brevity) System.Console.WriteLine($"Hello, {name}! You are {age} years old."); } }
It's important to note that System.Console.ReadLine()
returns a string. You'll often need to convert it to other data types (like integers) using methods like `int.Parse()`, `double.Parse()`, etc. Robust code should include error handling (e.g., `try-catch` blocks) to handle cases where the input cannot be parsed correctly.
System.Console.Error
represents the standard error stream. It's used to output error messages, separate from regular output. It is typically unbuffered, so output appears immediately.
public class Example { public static void Main(string[] args) { try { // Some code that might throw an exception int zero=0; int result = 10 / zero; // Example: Division by zero } catch (System.DivideByZeroException ex) { System.Console.Error.WriteLine("An error occurred: " + ex.Message); System.Environment.ExitCode = 1; // Indicate an error to the operating system } } }
Using System.Console.Error
for errors allows you to distinguish error messages from normal output, which is useful for debugging and logging.