Master object-oriented programming, exception handling, and file operations in C#.
Learn to create classes, handle exceptions, and work with files.
Person class with properties, a constructor, and methods to demonstrate core OOP concepts.class Person
{
// Auto-implemented properties
public string Name { get; set; }
public int Age { get; set; }
}
Properties in C# combine getter/setter methods into a clean syntax. { get; set; } creates auto-implemented properties.public Person(string name, int age)
{
Name = name;
Age = age;
}
Constructors initialize objects when created with new. The name matches the class name and has no return type.public void Introduce()
{
Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");
}
Methods define behavior. public makes it accessible from outside the class.Person person1 = new Person("Alice", 25);
person1.Introduce();
Person person2 = new Person("Bob", 30);
Console.WriteLine($"{person2.Name} is {person2.Age}");private set; to make properties read-only from outsidethis keyword to reference current instancerecord for simple data classes (C# 9+)ToString() for custom string representationHi, I'm Alice and I'm 25 years old.
Hi, I'm Bob and I'm 30 years old.
Bob is 30 years old.
class Person { }public string Name { get; set; }public Person(string name, int age) { ... }Person p = new Person("Name", 25);p.Introduce();Review feedback below
try
{
// Code that might throw an exception
int result = 10 / 0; // This causes DivideByZeroException
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}try
{
string input = "abc";
int number = int.Parse(input); // FormatException
}
catch (FormatException ex)
{
Console.WriteLine("Invalid number format!");
}
catch (Exception ex) // Catch-all for other exceptions
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
Order matters! Catch specific exceptions before general ones.try
{
// Attempt operation
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
// Always executes (cleanup code)
Console.WriteLine("Cleanup complete.");
}
finally runs whether an exception occurred or not - perfect for cleanup.string input = "42";
if (int.TryParse(input, out int number))
{
Console.WriteLine($"Parsed: {number}");
}
else
{
Console.WriteLine("Invalid input");
}
TryParse is often better than catching exceptions for parsing.Exception without logging or re-throwingthrow; (not throw ex;) to preserve stack tracewhen keyword filters exceptions: catch (Exception ex) when (ex.Message.Contains("specific"))Attempting division...
Error: Cannot divide by zero!
Attempting to parse 'abc'...
Error: Invalid number format!
Finally block executed.
Using TryParse: Successfully parsed 42
try { risky code }catch (DivideByZeroException ex) { }finally { cleanup code }int.TryParse(str, out int result)ex.MessageReview feedback below
List<T> collections and use LINQ (Language Integrated Query) to query and transform data.using System.Collections.Generic;
List<int> numbers = new List<int>();
numbers.Add(5);
numbers.Add(2);
numbers.Add(8);
// Or use collection initializer:
List<int> numbers = new List<int> { 5, 2, 8, 1, 9, 3 };numbers.Add(10); // Add element
numbers.Remove(2); // Remove first occurrence of 2
numbers.Insert(0, 100); // Insert at index 0
int count = numbers.Count; // Get count (not Length!)
numbers.Sort(); // Sort in place
numbers.Reverse(); // Reverse in placeusing System.Linq;
// Filter with Where
var evens = numbers.Where(n => n % 2 == 0);
// Transform with Select
var doubled = numbers.Select(n => n * 2);
// Aggregate functions
int sum = numbers.Sum();
double avg = numbers.Average();
int max = numbers.Max();
int min = numbers.Min();
// Order
var sorted = numbers.OrderBy(n => n);
var descending = numbers.OrderByDescending(n => n);
// First/Last
int first = numbers.First();
int last = numbers.Last();// Get even numbers, double them, sort descending
var result = numbers
.Where(n => n % 2 == 0)
.Select(n => n * 2)
.OrderByDescending(n => n)
.ToList();.ToList() or .ToArray() to execute immediately=> is the lambda operator (arrow function)FirstOrDefault() returns default if empty (no exception)Any() to check if collection has elements matching conditionOriginal: 5 2 8 1 9 3
Count: 6
Sum: 28
Average: 4.67
Max: 9
Even numbers: 2 8
Doubled: 10 4 16 2 18 6
Sorted: 1 2 3 5 8 9
List<int> nums = new List<int> { 1, 2, 3 };numbers.Count (property)numbers.Sum()numbers.Where(n => n > 5)numbers.Select(n => n * 2)numbers.OrderBy(n => n)Review feedback below