Intermediate C# Programming

Welcome to the intermediate level of C# programming! In this section, we'll explore more advanced concepts and techniques that will help you become a more proficient C# developer. You'll learn about object-oriented programming, collections, and other essential topics.

Object-Oriented Programming in C#

Classes and Objects

Object-oriented programming (OOP) is a programming paradigm that uses objects to design applications and computer programs. In C#, everything is an object, and classes are the blueprints for creating objects.

public class Person
{
    // Properties
    public string Name { get; set; }
    public int Age { get; set; }

    // Constructor
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    // Method
    public void Introduce()
    {
        Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");
    }
}
Best Practice: Use properties instead of public fields to encapsulate your data and provide controlled access to it.

Exercise 1.1

Create a `Student` class that inherits from `Person` and adds a `Grade` property. Implement a method to display the student's information.

2. Inheritance and Polymorphism

Inheritance allows you to create new classes that reuse, extend, and modify the behavior defined in other classes. Polymorphism enables you to use a class exactly like its parent class while maintaining its own methods.

public abstract class Animal
{
    public string Name { get; set; }
    
    public virtual void MakeSound()
    {
        Console.WriteLine("Some sound");
    }

    public abstract void Move();
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");
    }

    public override void Move()
    {
        Console.WriteLine("Dog is running");
    }
}

public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow!");
    }

    public override void Move()
    {
        Console.WriteLine("Cat is walking");
    }
}

// Usage
Animal[] animals = new Animal[]
{
    new Dog { Name = "Buddy" },
    new Cat { Name = "Whiskers" }
};

foreach (var animal in animals)
{
    Console.WriteLine($"{animal.Name}:");
    animal.MakeSound();
    animal.Move();
}
Warning: Avoid deep inheritance hierarchies as they can make code harder to maintain. Consider using composition instead.

Exercise 2.1

Create a hierarchy of shapes (Circle, Rectangle, Triangle) with methods to calculate area and perimeter. Use polymorphism to handle different shapes uniformly.

3. Interfaces and Abstract Classes

Interfaces and abstract classes are used to define contracts and common functionality for classes. They help achieve loose coupling and better code organization.

// Interface
public interface ILogger
{
    void Log(string message);
    void LogError(string error);
}

// Abstract class
public abstract class BaseLogger : ILogger
{
    protected string _logPath;

    public BaseLogger(string logPath)
    {
        _logPath = logPath;
    }

    public abstract void Log(string message);
    
    public virtual void LogError(string error)
    {
        Log($"ERROR: {error}");
    }
}

// Concrete implementation
public class FileLogger : BaseLogger
{
    public FileLogger(string logPath) : base(logPath) { }

    public override void Log(string message)
    {
        File.AppendAllText(_logPath, $"{DateTime.Now}: {message}\n");
    }
}

// Another implementation
public class ConsoleLogger : BaseLogger
{
    public ConsoleLogger() : base(null) { }

    public override void Log(string message)
    {
        Console.WriteLine($"{DateTime.Now}: {message}");
    }
}
Best Practice: Use interfaces to define contracts and abstract classes to share common implementation details.

Exercise 3.1

Create a notification system with different types of notifications (Email, SMS, Push) using interfaces and abstract classes.

4. Generics

Generics allow you to define type-safe data structures without committing to actual data types. They help write reusable, type-safe code.

public class Repository where T : class
{
    private List _items = new List();

    public void Add(T item)
    {
        _items.Add(item);
    }

    public T Get(int index)
    {
        return _items[index];
    }

    public IEnumerable GetAll()
    {
        return _items;
    }

    public IEnumerable Find(Func predicate)
    {
        return _items.Where(predicate);
    }
}

// Usage
var userRepo = new Repository();
var productRepo = new Repository();

// Generic method
public static T Max(T a, T b) where T : IComparable
{
    return a.CompareTo(b) > 0 ? a : b;
}

Exercise 4.1

Create a generic cache system that can store any type of data with a time-to-live (TTL) feature.

5. LINQ (Language Integrated Query)

LINQ provides a consistent way to query and transform data from different sources. It makes data manipulation more readable and maintainable.

var numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Query syntax
var evenNumbers = from num in numbers
                 where num % 2 == 0
                 orderby num descending
                 select num;

// Method syntax
var oddNumbers = numbers.Where(n => n % 2 != 0)
                       .OrderByDescending(n => n)
                       .ToList();

// Aggregation
var sum = numbers.Sum();
var average = numbers.Average();
var max = numbers.Max();

// Grouping
var groupedNumbers = numbers.GroupBy(n => n % 2 == 0 ? "Even" : "Odd");

// Joining collections
var users = new List();
var orders = new List();

var userOrders = from user in users
                join order in orders on user.Id equals order.UserId
                select new { user.Name, order.Amount };
Best Practice: Use LINQ to write declarative, readable code for data manipulation. Consider performance implications for large datasets.

Exercise 5.1

Create a program that processes a list of products, using LINQ to filter, sort, and group them based on different criteria.

6. Exception Handling

Proper exception handling is crucial for writing robust applications. It helps manage errors gracefully and maintain application stability.

public class Calculator
{
    public double Divide(int a, int b)
    {
        if (b == 0)
            throw new DivideByZeroException("Division by zero is not allowed.");
        
        return a / (double)b;
    }
}

// Usage
try
{
    var calculator = new Calculator();
    var result = calculator.Divide(10, 0);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero!");
    _logger.LogError(ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("An unexpected error occurred.");
    _logger.LogError(ex.Message);
}
finally
{
    // Code that always executes
    Console.WriteLine("Operation completed.");
}
Warning: Only catch exceptions you can handle. Let other exceptions propagate up the call stack.

Exercise 6.1

Create a file processing system that handles various exceptions (file not found, access denied, invalid format) appropriately.

Final Project

Create a simple inventory management system using the concepts learned in this section. The system should:

  • Use inheritance to create different types of products
  • Implement an interface for inventory operations
  • Use generics for the repository
  • Include proper exception handling
  • Use LINQ for querying the inventory
  • Implement logging for important operations