Learn C# · 12/15

Advanced C# Features

9 min read

Welcome back, coder! 🚀

If you’ve made it this far, you know how to write a loop, build a class, and probably catch an exception (or at least stare blankly at the debugger when you don't). Now we are entering the territory that separates the "I know C# syntax" developers from the "I build scalable architectures" engineers.

We are going to look at features that make your code cleaner, faster, and significantly safer. We’ll cover how to stop writing the same code twice (Generics), how to make objects talk to each other without getting married (Delegates/Events), how to hack new methods into old classes (Extensions), and how to handle data that shouldn't change (Records).

Grab a fresh cup of coffee ☕ (or tea, we don't judge). Let's dive in.


1. Generics: Writing Type-Safe Reusable Code

The Definition

Generics allow you to write a class or method with a placeholder for the data type. You define the logic once, and the specific data type is specified when the code is instantiated or called.

The Problem: The "Copy-Paste" Nightmare

Imagine you need to manage a list of Integers. You write a class called IntList.
Next week, your boss asks for a list of Strings. You copy-paste IntList, rename it StringList, and change int to string everywhere.
Then they ask for a list of Users.

You are now maintaining three identical classes where the only difference is the data type. If you find a bug in one, you have to fix it in all three. This is a violation of the DRY (Don't Repeat Yourself) principle.

Old School Solution: You could use an object array (since everything in C# inherits from object).
The Catch: This forces Boxing (wrapping a value type in an object) and Unboxing (extracting it). This kills performance and is not type-safe. If you throw a string into a list expecting int, your app crashes at runtime. 💥

The Solution: <T> to the Rescue

Generics let us use a parameter (conventionally named T) to represent the type.

Practical Example: A Generic Repository

In the industry, you will rarely write a custom List (Microsoft did that for us with List<T>). However, you will write Generic Repositories for databases.

csharp
// The <T> is a placeholder. It tells C#: "I don't know what type this is yet, 
// but whatever it is, I'll refer to it as T."
public class Repository<T>
{
    private List<T> _data = new List<T>();

    public void Add(T item)
    {
        // We can treat item like a real object
        _data.Add(item);
        Console.WriteLine($"Added item of type: {typeof(T)}");
    }

    public T GetByIndex(int index)
    {
        if (index >= 0 && index < _data.Count)
        {
            return _data[index];
        }
        return default(T); // Returns null for classes, 0 for ints
    }
}

// Usage
public class Program 
{
    public static void Main()
    {
        // We define T as 'string' here
        Repository<string> stringRepo = new Repository<string>();
        stringRepo.Add("Hello World"); 

        // We define T as 'int' here
        Repository<int> intRepo = new Repository<int>();
        intRepo.Add(42); 
        
        // This line would cause a COMPILE TIME error, not a runtime crash. 
        // stringRepo.Add(100); // Red squiggly lines! Saves your life.
    }
}

Constraints (The "Bouncer" for your Generics)

Sometimes T is too vague. What if you want to call .Save() on T, but C# doesn't know if T has a Save method? You use Constraints.

csharp
// "where T : IEntity" means T MUST implement the IEntity interface
public class DatabaseSaver<T> where T : IEntity 
{
    public void SaveItem(T item)
    {
        // Because of the constraint, we know Id exists!
        Console.WriteLine($"Saving item with ID: {item.Id}"); 
    }
}

Industry Fact: List<T>, Dictionary<TKey, TValue>, and Task<T> are the backbone of modern C#. You use generics every time you make a list.


2. Delegates and Events: Publisher-Subscriber Pattern

The Definition

  • Delegate: A variable that holds a reference to a method (a type-safe function pointer).
  • Event: A wrapper around a delegate that prevents external classes from resetting the delegate (adds a layer of protection).

The Problem: Tight Coupling

Imagine you are building a Stock Trading app. When the price of Apple (AAPL) goes up, you need to:

  1. Update the UI.
  2. Send an email to the user.
  3. Log the change to a database.

If you write code like this inside the Stock class:

csharp
// BAD DESIGN
public void UpdatePrice(decimal newPrice) {
    _ui.Update();      // Stock shouldn't know about UI
    _email.Send();     // Stock shouldn't know about Email
    _db.Log();         // Stock shouldn't know about Database
}

You have created Spaghetti Code. If you want to add SMS notifications later, you have to modify the Stock class (breaking the Open/Closed principle).

The Solution: "Don't Call Us, We'll Call You"

We use the Publisher-Subscriber (Pub-Sub) pattern. The Stock class (Publisher) shouts "The price changed!", and the UI/Email/Database (Subscribers) listen and react.

Modern Standards: Action and Func

In the old days, we declared custom delegates. In modern C#, we use the built-in Action (void return) and Func (returns a value).

csharp
public class StockMarket
{
    // 1. Define the Event using Action
    // Action<decimal> means a method that takes a decimal and returns void.
    // The 'event' keyword protects this so outsiders can only subscribe (+=) or unsubscribe (-=).
    public event Action<decimal> OnPriceChanged;

    public void UpdatePrice(decimal newPrice)
    {
        Console.WriteLine($"\nMARKET: Price updated to {newPrice}");
        
        // 2. Raise the event (Check if anyone is listening first with ?)
        OnPriceChanged?.Invoke(newPrice);
    }
}

public class UserInterface
{
    public void UpdateLabel(decimal price) => Console.WriteLine($"UI: Displaying green arrow ${price}");
}

public class Bot
{
    public void BuyOrSell(decimal price) 
    {
        if(price < 50) Console.WriteLine("BOT: Buying! Cheap!");
        else Console.WriteLine("BOT: Selling! Profit!");
    }
}

// Usage
var market = new StockMarket();
var ui = new UserInterface();
var bot = new Bot();

// 3. Subscription (Plugging in the cables)
market.OnPriceChanged += ui.UpdateLabel;
market.OnPriceChanged += bot.BuyOrSell;

// Trigger
market.UpdatePrice(40);
// Output: 
// MARKET: Price updated to 40
// UI: Displaying green arrow $40
// BOT: Buying! Cheap!

market.UpdatePrice(100);
// Output:
// MARKET: Price updated to 100
// UI: Displaying green arrow $100
// BOT: Selling! Profit!

Imagination Time: Think of an Event as a YouTube Notification Bell 🔔. The YouTuber (Publisher) uploads a video. They don't personally call you, your mom, and your neighbor. They just hit "Publish". Whoever clicked the bell (Subscribed) gets the notification. If you unsubscribe, the YouTuber keeps uploading, you just stop hearing about it.


3. Extension Methods: Adding Superpowers to Existing Classes

The Definition

Extension methods allow you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

The Problem: "I wish String had a WordCount method"

You are working with string. You constantly need to count how many words are in a sentence.
You cannot go into the Microsoft source code for System.String and add your method.
You could create a helper class: Helper.GetWordCount(myString). But that looks ugly and breaks the flow of code (e.g., str.Trim().ToLower()... wait, now I have to wrap it?).

The Solution: Static Classes + this

You can pretend to add a method to string.

csharp
// 1. Must be a static class
public static class StringExtensions
{
    // 2. Method must be static
    // 3. The first parameter uses 'this' to specify what we are extending
    public static int WordCount(this string str)
    {
        if (string.IsNullOrWhiteSpace(str)) return 0;
        
        return str.Split(new char[] { ' ', '.', '?' }, 
                         StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

// Usage
public class Program
{
    public static void Main()
    {
        string text = "C# is pretty cool.";
        
        // It looks like a native method!
        int count = text.WordCount(); 
        
        Console.WriteLine($"Word count: {count}"); // Output: 4
    }
}

LINQ: The Ultimate Extension

Did you know? LINQ (Language Integrated Query) is entirely built on Extension Methods. Methods like .Where(), .Select(), and .First() are just extension methods added to IEnumerable<T>.

Warning: Don't go crazy. If you add .Meow() to the Integer class, your coworkers will hate you. Only add extensions that make logical sense for the type.


4. Pattern Matching and Records for Immutable Data

The Definition

  • Records: A special reference type (introduced in C# 9) designed primarily for immutable data models. They compare by value, not by reference.
  • Pattern Matching: Syntax that tests an expression against a specific characteristic (type, value, or property structure).

The Problem: Boilerplate and Mutability

  1. Boilerplate: To create a class meant only to hold data (like Person), you need a constructor, properties, and if you want to compare them, you have to override .Equals() and .GetHashCode(). That is 50 lines of code for nothing.
  2. Mutability: If you pass a User object to a method, that method might change the User.Id by accident. This causes bugs that are impossible to trace.

The Solution: record and switch expressions

Records: The One-Liner Class

csharp
// This one line creates a class with:
// - Constructor
// - Properties (init-only, meaning immutable)
// - Equality comparison (Value-based)
// - A pretty ToString() output
public record Person(string FirstName, string LastName);

// Usage
var p1 = new Person("John", "Doe");
var p2 = new Person("John", "Doe");

// With classes, this is False (different memory addresses).
// With records, this is TRUE (same data).
Console.WriteLine(p1 == p2); // True!

Non-Destructive Mutation (with):
Since records are immutable, you can't change p1.LastName. instead, you create a clone with changes.

csharp
var p3 = p1 with { LastName = "Smith" };
// p1 is still John Doe. p3 is John Smith.

Pattern Matching: The switch Glow-Up

Forget the old case 1: break;. Modern pattern matching is expressive.

csharp
public record Order(string Type, decimal Amount, string Region);

public static decimal CalculateTax(Order order)
{
    // Switch Expression
    return order switch
    {
        // Property Pattern: Checks values inside the object
        { Amount: 0 } => 0m, 
        
        // Logical combinations
        { Region: "US", Type: "Software" } => order.Amount * 0.08m,
        { Region: "EU" } => order.Amount * 0.20m,
        
        // The "Default" case (Discard pattern)
        _ => order.Amount * 0.10m
    };
}

Industry Standard: Use Records for DTOs (Data Transfer Objects), API responses, and Redux-style state management. Use Classes for services and objects that have logic/behavior and need to change state.


Summary Checklist 📝

  1. Generics: Use <T> to avoid code duplication and boxing. Used in List<T>, Task<T>.
  2. Delegates/Events: Use Action and Func to let objects communicate loosely. Used in UI programming (button clicks) and System integrations.
  3. Extensions: Use this Type name in static classes to improve readability. Used extensively in LINQ.
  4. Records/Patterns: Use record for data that shouldn't change. Use pattern matching for clean logic flows.

🔗 References & Further Reading

Happy Coding! 🐧

Challenge

Your task is to implement a small data processing and notification system using advanced C# features. You will need to define data models using records, add functionality to existing types with extension methods, create a generic repository that raises events, and use pattern matching to handle those events.

Instructions

  1. Define Records: Create two record types, Customer and Order, that both implement the IEntity interface.

    • Customer should have string Name, and string Email properties in addition to the Id from the interface.
    • Order should have Guid CustomerId, and decimal Amount properties in addition to the Id.
  2. Create an Extension Method: Implement a static class named StringExtensions. Inside it, create a public static extension method called IsValidEmail for the string type. This method should return true if the string contains an @ symbol, and false otherwise.

  3. Implement Generic Repository: Complete the Repository<T> class.

    • Add a generic constraint to ensure that T must be a type that implements IEntity.
    • Declare a public event named ItemAdded using the Action<T> delegate.
    • In the Add method, invoke the ItemAdded event, passing the newly added item.
  4. Use Pattern Matching: Complete the OnItemAdded method in the NotificationService class. This method will act as an event handler. Use a switch statement or a switch expression on the item parameter to implement the following logic:

    • A case that matches if the item is a Customer whose Email property returns true from your IsValidEmail extension method.
    • A case that matches if the item is an Order whose Amount is greater than 500.0m.
    • A default case (_) for any other type of item.

Expected result

Your final code should correctly implement all four required components. The solution should contain:

  1. The Customer and Order record definitions, both implementing IEntity and including the required properties.
  2. A public static class StringExtensions containing the public static bool IsValidEmail(this string email) method.
  3. The Repository<T> class signature with the where T : IEntity constraint.
  4. Inside the Repository<T> class, a public event declaration like public event Action<T> ItemAdded; and the invocation call ItemAdded?.Invoke(item); inside the Add method.
  5. Inside the OnItemAdded method, a switch statement or expression that correctly uses pattern matching. It should include a case for a Customer with a property pattern and a when clause that calls the extension method (e.g., case Customer c when c.Email.IsValidEmail():), a case for an Order with a property pattern checking the amount (e.g., case Order { Amount: > 500.0m }:), and a default _ case.
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.