C# Programming Labs

Master object-oriented programming, exception handling, and file operations in C#.

OOP & Error Handling - Module 3

Learn to create classes, handle exceptions, and work with files.

Lab 7: Classes & Object-Oriented Programming
Advanced
Coding Challenge
Your Task: Create a Person class with properties, a constructor, and methods to demonstrate core OOP concepts.

Detailed Requirements:
1. Create a class with properties:
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.

2. Add a constructor:
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.

3. Add a method:
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.

4. Create objects and call methods:
Person person1 = new Person("Alice", 25); person1.Introduce(); Person person2 = new Person("Bob", 30); Console.WriteLine($"{person2.Name} is {person2.Age}");

💡 Pro Tips:
• Use private set; to make properties read-only from outside
• Add validation in property setters for data integrity
• Use this keyword to reference current instance
• Consider using record for simple data classes (C# 9+)
• Override ToString() for custom string representation

Expected Output:
Hi, I'm Alice and I'm 25 years old. Hi, I'm Bob and I'm 30 years old. Bob is 30 years old.

Requirements Checklist

Create a class named Person
Add Name and Age properties with get/set
Create a constructor with parameters
Add an Introduce() method
Create at least 2 Person objects
Call methods and access properties
Output
// Click "Run Code" to compile and execute
Hints & Tips
• Class syntax: class Person { }
• Property: public string Name { get; set; }
• Constructor: public Person(string name, int age) { ... }
• Create object: Person p = new Person("Name", 25);
• Call method: p.Introduce();
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 8: Exception Handling
Advanced
Coding Challenge
Your Task: Implement proper exception handling using try-catch-finally blocks to handle potential errors gracefully.

Detailed Requirements:
1. Basic try-catch structure:
try { // Code that might throw an exception int result = 10 / 0; // This causes DivideByZeroException } catch (DivideByZeroException ex) { Console.WriteLine($"Error: {ex.Message}"); }

2. Handle multiple exception types:
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.

3. Use finally block:
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.

4. Parse user input safely with TryParse:
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.

💡 Pro Tips:
• Never catch Exception without logging or re-throwing
• Use throw; (not throw ex;) to preserve stack trace
• Don't use exceptions for flow control
• Create custom exceptions for domain-specific errors
• when keyword filters exceptions: catch (Exception ex) when (ex.Message.Contains("specific"))

Expected Output:
Attempting division... Error: Cannot divide by zero! Attempting to parse 'abc'... Error: Invalid number format! Finally block executed. Using TryParse: Successfully parsed 42

Requirements Checklist

Use try block to wrap risky code
Catch DivideByZeroException
Catch FormatException for parsing errors
Use finally block for cleanup
Use TryParse for safe parsing
Print appropriate error messages
Output
// Click "Run Code" to compile and execute
Hints & Tips
• Try block: try { risky code }
• Catch specific: catch (DivideByZeroException ex) { }
• Finally: finally { cleanup code }
• TryParse: int.TryParse(str, out int result)
• Access message: ex.Message
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 9: Lists & LINQ Basics
Advanced
Coding Challenge
Your Task: Work with List<T> collections and use LINQ (Language Integrated Query) to query and transform data.

Detailed Requirements:
1. Create and populate a List:
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 };

2. List operations:
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 place

3. LINQ queries (add using System.Linq):
using 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();

4. Chain LINQ methods:
// Get even numbers, double them, sort descending var result = numbers .Where(n => n % 2 == 0) .Select(n => n * 2) .OrderByDescending(n => n) .ToList();

💡 Pro Tips:
• LINQ uses deferred execution - query runs when iterated
• Use .ToList() or .ToArray() to execute immediately
• => is the lambda operator (arrow function)
• FirstOrDefault() returns default if empty (no exception)
• Use Any() to check if collection has elements matching condition

Expected Output:
Original: 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

Requirements Checklist

Create a List<int> with values
Use .Count property
Use LINQ Sum(), Average(), or Max()
Use Where() to filter elements
Use Select() to transform elements
Use OrderBy() or Sort()
Output
// Click "Run Code" to compile and execute
Hints & Tips
• Create List: List<int> nums = new List<int> { 1, 2, 3 };
• Count: numbers.Count (property)
• Sum: numbers.Sum()
• Filter: numbers.Where(n => n > 5)
• Transform: numbers.Select(n => n * 2)
• Sort: numbers.OrderBy(n => n)
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below