C# Output - Displaying Data
Introduction to Output in C#
In C#, the main way to display information in a console application is through the Console class from the System namespace. It provides methods to write text, numbers, and other values to the output window.
Learning to use output effectively is important for debugging, interacting with users, and showing program results.
Basic Output Methods
The Console class provides two commonly used methods for output:
- Console.WriteLine() writes text and then moves the cursor to the next line.
- Console.Write() writes text but keeps the cursor on the same line.
using System;
namespace OutputBasics
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine("This is on a new line.");
Console.Write("Hello, ");
Console.Write("World!");
string name = "Alice";
int age = 25;
Console.WriteLine("\nName: " + name + ", Age: " + age);
Console.WriteLine($"Name: {name}, Age: {age}");
}
}
}
Hello, World! This is on a new line. Hello, World! Name: Alice, Age: 25 Name: Alice, Age: 25
Formatting Output
C# provides several ways to format output for numbers, dates, and text alignment:
- Standard numeric format strings (e.g., currency, fixed point, numeric).
- Date and time format specifiers.
- Alignment and padding for neat tabular output.
using System;
namespace FormattingOutput
{
class Program
{
static void Main(string[] args)
{
double number = 1234.5678;
Console.WriteLine("Default: " + number);
Console.WriteLine("Currency: {0:C}", number);
Console.WriteLine("Fixed point: {0:F2}", number);
Console.WriteLine("Numeric: {0:N}", number);
DateTime today = new DateTime(2023, 10, 15);
Console.WriteLine("Short date: {0:d}", today);
Console.WriteLine("Long date: {0:D}", today);
Console.WriteLine("Custom format: {0:yyyy-MM-dd}", today);
string[] names = {"Alice", "Bob", "Charlie"};
int[] ages = {25, 30, 35};
Console.WriteLine("\nName\t\tAge");
Console.WriteLine("----\t\t---");
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine($"{names[i],-10}\t{ages[i],3}");
}
}
}
}
Default: 1234.5678 Currency: $1,234.57 Fixed point: 1234.57 Numeric: 1,234.57 Short date: 10/15/2023 Long date: Sunday, October 15, 2023 Custom format: 2023-10-15 Name Age ---- --- Alice 25 Bob 30 Charlie 35