A fluent interface lets you write code that reads like a sentence by chaining method calls. Extensions add new methods to existing classes without changing them.
0
0
Fluent interface with extensions in C Sharp (C#)
Introduction
When you want to make code easier to read and write by chaining actions.
When you want to add new features to a class without modifying its source code.
When building APIs or libraries that should feel natural and expressive to use.
When you want to configure objects step-by-step in a clear way.
When you want to improve code readability in complex object setups.
Syntax
C Sharp (C#)
public static class ExtensionClassName { public static ReturnType MethodName(this TargetType obj, OtherParameters) { // method body return obj; // to allow chaining } }
The this keyword before the first parameter means this method extends that type.
Return the object itself to allow chaining multiple calls in a fluent style.
Examples
This adds a method to
string that adds an exclamation mark.C Sharp (C#)
public static class StringExtensions { public static string AddExclamation(this string s) { return s + "!"; } }
These extensions let you set properties on
Person in a chain.C Sharp (C#)
public class Person { public string Name { get; set; } public int Age { get; set; } } public static class PersonExtensions { public static Person SetName(this Person p, string name) { p.Name = name; return p; } public static Person SetAge(this Person p, int age) { p.Age = age; return p; } }
Sample Program
This program creates a Person and uses extension methods to set the name, age, and increase age by one. The calls chain fluently for clear, readable code.
C Sharp (C#)
using System; public class Person { public string Name { get; set; } public int Age { get; set; } public override string ToString() => $"Name: {Name}, Age: {Age}"; } public static class PersonExtensions { public static Person SetName(this Person p, string name) { p.Name = name; return p; } public static Person SetAge(this Person p, int age) { p.Age = age; return p; } public static Person CelebrateBirthday(this Person p) { p.Age += 1; return p; } } class Program { static void Main() { var person = new Person() .SetName("Alice") .SetAge(30) .CelebrateBirthday(); Console.WriteLine(person); } }
OutputSuccess
Important Notes
Extension methods must be in a static class.
Fluent interfaces improve readability but avoid making chains too long or complex.
You cannot override behavior of sealed classes with extension methods; you can only add new methods.
Summary
Fluent interfaces let you chain method calls for easy reading.
Extension methods add new methods to existing types without changing them.
Return the object itself in extensions to enable chaining.