Search⌘ K
AI Features

Extension Methods

Explore how to extend existing classes and structs in C# using various techniques. Learn to update source code, use inheritance, and create extension methods to add new behaviors, especially when modifying sealed types or inaccessible source code. Understand the syntax and usage of extension methods and how they provide flexible solutions for enhancing functionality without altering original classes.

We often need to extend the functionality of a class or struct. We can use several approaches depending on the type and our access to the source code.

Update source code

We could go to the source code of the type and make whatever changes we need. Consider the following Printer class. Its purpose is to print the Message property in a variety of ways. If we need additional functionality, we can simply add another method or edit existing ones.

C# 14.0
namespace MainProgram;
public class Printer
{
public string Message { get; set; }
public Printer(string message)
{
Message = message;
}
// We can change this method or add another one
public void PrintWithDashes()
{
Console.WriteLine($"###{Message}###");
}
}
  • Line 1: We declare a file-scoped namespace to organize our code without extra indentation.

  • Line 3: We define the Printer class.

  • Lines 5–10: We define a property and a constructor to initialize the printer with a message.

  • Lines 13–16: We add a new method PrintWithDashes directly to the class.

This approach is only useful if we control the source code of the type we want to modify. This isn’t possible in most cases ...