C# Output
Display data and messages to users
🖥️ C# Output Methods
Output displays information to users. C# uses Console.WriteLine() and Console.Write() to print text, numbers, and variables to the console window.
using System;
class Output
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}
Output:
Hello, World!
Output Methods
WriteLine()
Prints text with a new line at the end
Console.WriteLine("Line 1");
Console.WriteLine("Line 2");
Write()
Prints text without a new line
Console.Write("Same ");
Console.Write("Line");
Numbers
Display numeric values directly
Console.WriteLine(42);
Console.WriteLine(3.14);
Variables
Print variable values
int age = 25;
Console.WriteLine(age);
🔹 Console.WriteLine()
The Console.WriteLine() method in C# outputs text to the console and automatically appends a newline character at the end. This means each call to WriteLine() moves the cursor to the beginning of the next line, making it perfect for displaying separate lines of output clearly. For example, Console.WriteLine("First line"); Console.WriteLine("Second line"); will print two distinct lines. It’s commonly used for messages, debugging logs, and formatted data displays where line separation improves readability. You can pass strings, numbers, variables, or expressions directly into the method for versatile output.
using System;
class WriteLineExample
{
static void Main()
{
Console.WriteLine("First line");
Console.WriteLine("Second line");
Console.WriteLine("Third line");
// Print numbers
Console.WriteLine(100);
Console.WriteLine(3.14159);
}
}
Output:
First line
Second line
Third line
100
3.14159
🔹 Console.Write()
The Console.Write() method prints text to the console without moving to a new line after execution. Unlike WriteLine(), it keeps the cursor on the same line, allowing subsequent output to continue directly after the previous text. This is particularly useful for creating formatted outputs, progress indicators, or prompts where content needs to stay inline. For instance, Console.Write("Hello "); Console.Write("World!"); produces "Hello World!" on a single line. It supports all data types and string concatenation, making it essential for building dynamic, single-line console interfaces.
using System;
class WriteExample
{
static void Main()
{
Console.Write("Hello ");
Console.Write("World");
Console.Write("!");
Console.WriteLine(); // Move to new line
Console.Write("A");
Console.Write("B");
Console.Write("C");
}
}
Output:
Hello World!
ABC
🔹 Printing Variables
Printing variables in C# involves outputting their stored values directly to the console using WriteLine() or Write(). You can print variables alone or combine them with descriptive text using concatenation (+ operator) for clearer context. For example, int age = 25; Console.WriteLine("Age: " + age); displays "Age: 25". This works with all data types—strings, integers, booleans, and decimals—making it invaluable for debugging and user feedback. Properly formatted variable output enhances program transparency and helps users understand the data being processed.
using System;
class Variables
{
static void Main()
{
string name = "Alice";
int age = 25;
double height = 5.6;
bool isStudent = true;
// Print variables directly
Console.WriteLine(name);
Console.WriteLine(age);
// Combine text and variables
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
Console.WriteLine("Height: " + height + " feet");
Console.WriteLine("Student: " + isStudent);
}
}
Output:
Alice
25
Name: Alice
Age: 25
Height: 5.6 feet
Student: True
🔹 String Concatenation
String concatenation remains a foundational technique in C# for joining multiple string values into one cohesive output. Using the + operator, developers can combine literals, variables, and expressions, such as "Hello, " + userName + "!". While intuitive, excessive concatenation in loops can impact performance due to string immutability. For repeated operations, StringBuilder is more efficient. Understanding when to use concatenation versus interpolation or StringBuilder is key for writing optimized, maintainable code that produces clear, user-friendly text outputs in applications ranging from console programs to web interfaces.
using System;
class Concatenation
{
static void Main()
{
string firstName = "John";
string lastName = "Doe";
int age = 30;
// Concatenate strings
Console.WriteLine(firstName + " " + lastName);
// Concatenate strings and numbers
Console.WriteLine("Name: " + firstName + " " + lastName);
Console.WriteLine(firstName + " is " + age + " years old");
// Multiple concatenations
string fullInfo = "User: " + firstName + ", Age: " + age;
Console.WriteLine(fullInfo);
}
}
Output:
John Doe
Name: John Doe
John is 30 years old
User: John, Age: 30
🔹 String Interpolation
String interpolation in C# offers a streamlined syntax for embedding variables and expressions within strings by prefixing with $ and wrapping them in {}. It eliminates the clutter of concatenation operators and improves code clarity. For instance, $"The result is {value * 2}" directly incorporates calculations. Interpolation also supports formatting specifiers, such as {price:C2} for currency. This method is not only more readable but also reduces runtime errors from incorrect string assembly, making it a best practice for generating dynamic text in modern C# development.
using System;
class Interpolation
{
static void Main()
{
string name = "Sarah";
int age = 28;
double salary = 50000.50;
// String interpolation (easier to read)
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"{name} is {age} years old");
Console.WriteLine($"Salary: ${salary}");
// Can include expressions
Console.WriteLine($"Next year: {age + 1}");
Console.WriteLine($"Monthly: ${salary / 12}");
}
}
Output:
Name: Sarah
Age: 28
Sarah is 28 years old
Salary: $50000.5
Next year: 29
Monthly: $4166.708333333333
🔹 Formatting Numbers
Formatting numbers in C# controls how numeric values appear when converted to strings, using standard or custom format specifiers. This includes setting decimal places, currency symbols, percentage signs, and digit grouping. For example, price.ToString("C2") formats as currency with two decimals, like "$19.99". Common specifiers include "N" for number formatting, "P" for percentages, and "F" for fixed-point. Proper number formatting improves data presentation in reports, user interfaces, and financial applications, ensuring clarity, localization, and professional appearance in output.
using System;
class Formatting
{
static void Main()
{
double price = 19.99;
double percent = 0.85;
int number = 1234567;
// Currency format
Console.WriteLine($"Price: {price:C}");
// Fixed decimal places
Console.WriteLine($"Value: {price:F2}");
// Percentage
Console.WriteLine($"Score: {percent:P}");
// Number with commas
Console.WriteLine($"Population: {number:N0}");
}
}
Output:
Price: $19.99
Value: 19.99
Score: 85.00%
Population: 1,234,567
🔹 Escape Sequences
Escape sequences create special characters in strings. Use backslash (\) followed by a character to create tabs, new lines, and quotes.
Common Escape Sequences:
-
\n- New line -
\t- Tab -
\"- Double quote -
\'- Single quote -
\\- Backslash
using System;
class EscapeSequences
{
static void Main()
{
// New line
Console.WriteLine("Line 1\nLine 2");
// Tab
Console.WriteLine("Name:\tJohn");
Console.WriteLine("Age:\t25");
// Quotes
Console.WriteLine("She said \"Hello\"");
// Backslash
Console.WriteLine("Path: C:\\Users\\Documents");
}
}
Output:
Escape sequences in C# are special character combinations starting with a backslash (\) that represent non-printable characters or symbols within strings. They allow you to include formatting and special characters directly in your text output. For example, \n creates a new line, \t inserts a tab for alignment, \" displays a double quote inside a string, and \\ shows a literal backslash. This is essential for formatting console output, defining file paths (e.g., "C:\\Users\\Documents"), and including quotes in messages without breaking the string syntax, making your output cleaner and more readable.