Extension Methods & Fluent APIs
Add reusable behavior to existing types with extension methods and design fluent APIs whose calls read like a sequence of instructions.
Part 1: What You Will Learn
Add reusable behavior to existing types with extension methods and design fluent APIs whose calls read like a sequence of instructions.
- Declare an extension method in a static class using the `this` modifier on the first parameter.
- Call an extension method as if it were an instance method.
- Return `this` from builder methods to support method chaining.
- Keep extension methods focused so they improve readability rather than hide complex work.
Project setup: Create a .NET 10 Console App. Add the classes below to Program.cs or separate files.
Part 2: Topic-Specific Working Example
The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.
public static class StringExtensions
{
public static string ToSlug(this string text)
{
return text.Trim()
.ToLowerInvariant()
.Replace(" ", "-");
}
}
public sealed class ReportBuilder
{
private string _title = "Untitled";
private bool _includeTotals;
public ReportBuilder WithTitle(string title)
{
_title = title;
return this;
}
public ReportBuilder IncludeTotals()
{
_includeTotals = true;
return this;
}
public string Build()
{
return $"Report: {_title} | Totals: {_includeTotals}";
}
}
string slug = "Quarterly Sales Report".ToSlug();
string report = new ReportBuilder()
.WithTitle("Quarterly Sales")
.IncludeTotals()
.Build();
Console.WriteLine(slug);
Console.WriteLine(report);Part 3: How the Code Works
- `ToSlug(this string text)` extends `string` without modifying the .NET `String` class.
- The compiler translates `value.ToSlug()` into a call to the static extension method.
- `WithTitle()` and `IncludeTotals()` return the same builder object, enabling a fluent chain.
- `Build()` ends the chain and produces the final result.
Part 4: Mini Project & Practice
Mini project: create an EmailBuilder with To(), Subject(), AddLine(), and Build() methods. Add an extension method named Truncate(this string text, int length) for preview text.
Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.
When you are comfortable with this lesson, continue to Lesson 20.
C# in Visual Studio 2026
📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.
View on Amazon Kindle Edition