Easy Learn C#

C# Output

Console Output

To output text to the console in C#, you use the Console.WriteLine() and Console.Write() methods.

Example:


// WriteLine adds a new line after the output
Console.WriteLine("Hello World!");
Console.WriteLine("I am learning C#");

// Write doesn't add a new line
Console.Write("Hello ");
Console.Write("World");  // Output: Hello World (on the same line)
                            
  • Console.WriteLine() prints the specified text followed by a new line
  • Console.Write() prints the specified text without a new line

Console Input

To receive input from users in console applications, you use the Console.ReadLine() method. This allows your program to wait for the user to type something and press Enter.

Basic Input:


// Prompt the user for input
Console.Write("Enter your name: ");

// Wait for the user to type and press Enter
string name = Console.ReadLine();

// Display the input
Console.WriteLine($"Hello, {name}!");
                            

Converting String Input to Other Types:


// Get numeric input
Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();

// Convert string to integer
int age = Convert.ToInt32(ageInput);
// or
int age = int.Parse(ageInput);

Console.WriteLine($"Next year, you will be {age + 1} years old.");
                            

Safe Input Handling:


// Handling potential invalid input
Console.Write("Enter a number: ");
string userInput = Console.ReadLine();

// Try to parse, with graceful error handling
if (int.TryParse(userInput, out int number)) {
    Console.WriteLine($"You entered the number: {number}");
} else {
    Console.WriteLine("That's not a valid number!");
}
                            

Important notes about Console.ReadLine():

  • Always returns the input as a string, regardless of what the user types
  • Waits for the user to press Enter before continuing execution
  • Returns an empty string if the user just presses Enter without typing anything
  • Returns null if the end of the input stream is reached (rare in typical applications)

Formatting Output

You can format your output in different ways:

String Concatenation:


string name = "John";
int age = 25;
Console.WriteLine("Name: " + name + ", Age: " + age);
                            

String Formatting (composite formatting):


string name = "John";
int age = 25;
Console.WriteLine("Name: {0}, Age: {1}", name, age);
                            

String Interpolation (recommended, C# 6.0 and later):


string name = "John";
int age = 25;
Console.WriteLine($"Name: {name}, Age: {age}");
                            

Formatting Numbers and Dates

You can format numbers and dates using format specifiers:

Currency Formatting:


double price = 123.45;
Console.WriteLine($"Price: {price:C}");  // Outputs: Price: $123.45 (in US culture)
                            

Number Formatting:


double number = 12345.6789;
Console.WriteLine($"Number: {number:N2}");  // Outputs: Number: 12,345.68 (formatted with commas and 2 decimal places)
Console.WriteLine($"Percentage: {0.75:P0}");  // Outputs: Percentage: 75%
                            

Date Formatting:


DateTime now = DateTime.Now;
Console.WriteLine($"Date: {now:d}");  // Outputs: Date: 5/10/2023 (short date format)
Console.WriteLine($"Time: {now:t}");  // Outputs: Time: 10:30 AM (short time format)
Console.WriteLine($"Full: {now:F}");  // Outputs: Full: Friday, May 10, 2023 10:30:45 AM
                            

Special Characters

You can include special characters in your output using escape sequences:


// Using escape sequences
Console.WriteLine("Hello\nWorld");  // Outputs Hello and World on separate lines
Console.WriteLine("I am learning \"C#\"");  // Outputs: I am learning "C#"
Console.WriteLine("Path: C:\\Program Files\\App");  // Outputs: Path: C:\Program Files\App

// Using verbatim strings (preceded by @)
Console.WriteLine(@"Path: C:\Program Files\App");  // No need to escape backslashes
Console.WriteLine(@"This is a
multi-line
string");  // Preserves line breaks
                            

Common escape sequences:

  • \n - New line
  • \t - Tab
  • \" - Double quote
  • \' - Single quote
  • \\ - Backslash
  • \r - Carriage return