Learn C# Programming
Master C# programming from basics to advanced concepts with our comprehensive tutorial series. Perfect for beginners and experienced developers.
C# Input and Output
Input and output operations allow your program to interact with users and external data sources. C# provides various methods for reading input and displaying output.
Console Output
1. Console.WriteLine()
Displays text and moves to the next line:
Console.WriteLine("Hello, World!");
Console.WriteLine("This is on a new line");
// Output variables
int age = 25;
string name = "John";
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
2. Console.Write()
Displays text without moving to the next line:
Console.Write("Enter your name: ");
Console.Write("Hello ");
Console.Write("World");
// Output: Enter your name: Hello World
3. String Interpolation
Modern way to format output using $ prefix:
string name = "Alice";
int age = 30;
double salary = 50000.50;
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Salary: {salary:C}"); // Currency format
Console.WriteLine($"Percentage: {0.85:P}"); // Percentage format
Console.WriteLine($"Date: {DateTime.Now:yyyy-MM-dd}");
4. String.Format()
Traditional string formatting method:
string name = "Bob";
int score = 95;
Console.WriteLine(String.Format("Student: {0}, Score: {1}", name, score));
Console.WriteLine("Student: {0}, Score: {1:F2}", name, score);
Console Input
1. Console.ReadLine()
Reads a complete line of text from the user:
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
2. Console.ReadKey()
Reads a single key press:
Console.WriteLine("Press any key to continue...");
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine($"\nYou pressed: {keyInfo.Key}");
// Read key without displaying it
Console.WriteLine("Enter password: ");
ConsoleKeyInfo key = Console.ReadKey(true); // true = don't display
3. Converting Input
Converting string input to other data types:
// Converting to integer
Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
int age = int.Parse(ageInput);
// Safe conversion with TryParse
Console.Write("Enter a number: ");
string numberInput = Console.ReadLine();
if (int.TryParse(numberInput, out int number))
{
Console.WriteLine($"You entered: {number}");
}
else
{
Console.WriteLine("Invalid number format");
}
// Converting to double
Console.Write("Enter your height: ");
double height = double.Parse(Console.ReadLine());
// Converting to boolean
Console.Write("Are you a student? (true/false): ");
bool isStudent = bool.Parse(Console.ReadLine());
Formatting Output
1. Numeric Formatting
double value = 1234.5678;
Console.WriteLine($"{value:F2}"); // 1234.57 (2 decimal places)
Console.WriteLine($"{value:C}"); // $1,234.57 (currency)
Console.WriteLine($"{value:N}"); // 1,234.57 (number with commas)
Console.WriteLine($"{value:P}"); // 123,456.78% (percentage)
Console.WriteLine($"{value:E}"); // 1.234568E+003 (scientific)
int intValue = 42;
Console.WriteLine($"{intValue:D5}"); // 00042 (pad with zeros)
Console.WriteLine($"{intValue:X}"); // 2A (hexadecimal)
2. Date and Time Formatting
DateTime now = DateTime.Now;
Console.WriteLine($"{now:yyyy-MM-dd}"); // 2024-01-15
Console.WriteLine($"{now:HH:mm:ss}"); // 14:30:25
Console.WriteLine($"{now:dddd, MMMM dd, yyyy}"); // Monday, January 15, 2024
Console.WriteLine($"{now:hh:mm tt}"); // 02:30 PM
File Input/Output
1. Reading from Files
// Read entire file
string content = File.ReadAllText("data.txt");
Console.WriteLine(content);
// Read all lines
string[] lines = File.ReadAllLines("data.txt");
foreach (string line in lines)
{
Console.WriteLine(line);
}
// Read line by line (memory efficient)
using (StreamReader reader = new StreamReader("data.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
2. Writing to Files
// Write entire text
File.WriteAllText("output.txt", "Hello, World!");
// Write multiple lines
string[] lines = { "Line 1", "Line 2", "Line 3" };
File.WriteAllLines("output.txt", lines);
// Append to file
File.AppendAllText("output.txt", "\nAppended text");
// Write using StreamWriter
using (StreamWriter writer = new StreamWriter("output.txt"))
{
writer.WriteLine("First line");
writer.WriteLine("Second line");
}
Error Handling for I/O
try
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
Console.WriteLine($"You entered: {number}");
}
catch (FormatException)
{
Console.WriteLine("Error: Please enter a valid number");
}
catch (OverflowException)
{
Console.WriteLine("Error: Number is too large");
}
// File I/O error handling
try
{
string content = File.ReadAllText("nonexistent.txt");
}
catch (FileNotFoundException)
{
Console.WriteLine("Error: File not found");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Error: Access denied");
}
💡 Best Practices
- Always validate user input before processing
- Use
TryParsemethods for safe type conversion - Use string interpolation ($"") for readable formatting
- Handle exceptions when reading files or parsing input
- Use
usingstatements for file operations to ensure proper disposal - Provide clear prompts for user input
Frequently Asked Questions
Master C# Programming with Our Comprehensive Tutorial
Our C# programming tutorial is designed to take you from a complete beginner to an advanced developer. Whether you're looking to build web applications, desktop software, or mobile apps, C# provides the foundation you need for modern software development.
Start with the basics like variables, data types, and control structures, then progress to advanced topics including object-oriented programming, LINQ, async programming, and more. Each lesson includes practical examples and exercises to reinforce your learning.
Join thousands of developers who have learned C# programming through our step-by-step tutorials. Begin your journey today and unlock the power of .NET development.