📖 Scenario: Imagine you are building a simple text formatter for a chat application. You want to create a way to style messages by chaining methods like Bold(), Italic(), and Underline() in a smooth, readable way.
🎯 Goal: Build a fluent interface using extension methods that allows chaining text styling methods on a string. The final output should show the styled text with tags representing the styles.
📋 What You'll Learn
Create a class called TextFormatter that holds a string value.
Create extension methods Bold(), Italic(), and Underline() for TextFormatter.
Each extension method should wrap the current text with corresponding tags: <b>, <i>, and <u> respectively.
Allow chaining of these extension methods to apply multiple styles.
Add a method GetText() to return the final styled string.
💡 Why This Matters
🌍 Real World
Fluent interfaces are common in libraries and frameworks to make code easier to read and write, such as building queries, configuring settings, or styling text.
💼 Career
Understanding fluent interfaces and extension methods is valuable for C# developers, especially when working with APIs like LINQ, Entity Framework, or UI frameworks.
Progress0 / 4 steps
1
Create the TextFormatter class
Create a public class called TextFormatter with a public string property called Text. Add a constructor that takes a string parameter called text and sets the Text property.
C Sharp (C#)
Hint
Remember to create a constructor that sets the Text property from the parameter.
2
Add the Bold extension method
Create a public static class called TextFormatterExtensions. Inside it, create a public static method called Bold that takes a TextFormatter parameter named formatter with the this keyword. The method should wrap formatter.Text with <b> and </b> tags, update formatter.Text, and return the formatter object.
C Sharp (C#)
Hint
Use this TextFormatter formatter as the first parameter to make it an extension method.
3
Add Italic and Underline extension methods
Inside the TextFormatterExtensions class, add two more public static extension methods: Italic and Underline. Both take a TextFormatter parameter named formatter with this. Italic should wrap formatter.Text with <i> and </i>. Underline should wrap formatter.Text with <u> and </u>. Both methods update formatter.Text and return formatter.
C Sharp (C#)
Hint
Follow the same pattern as Bold for both Italic and Underline.
4
Use the fluent interface and print the result
In the Main method, create a new TextFormatter object with the text "Hello". Chain the extension methods Bold(), Italic(), and Underline() in that order. Then print the final Text property of the object using Console.WriteLine.
C Sharp (C#)
Hint
Remember to create the TextFormatter object first, then chain the extension methods, and finally print the Text property.
Practice
(1/5)
1. What is the main purpose of a fluent interface in C#?
easy
A. To automatically generate user interfaces
B. To improve performance by using unsafe code
C. To enforce strict type checking at compile time
D. To allow chaining of method calls for clearer and simpler code
Solution
Step 1: Understand fluent interface concept
A fluent interface is designed to let you chain method calls, making code easier to read and write.
Step 2: Compare options
Only To allow chaining of method calls for clearer and simpler code describes chaining method calls clearly. Other options describe unrelated concepts.
Final Answer:
To allow chaining of method calls for clearer and simpler code -> Option D
Quick Check:
Fluent interface = chaining methods [OK]
Hint: Fluent means chaining methods for easy reading [OK]
Common Mistakes:
Confusing fluent interface with performance optimization
Thinking fluent interface auto-generates UI
Mixing fluent interface with type checking
2. Which of the following is the correct syntax to define an extension method for a class Person that returns the same Person object to enable fluent chaining?
easy
A. public static void UpdateName(this Person p, string name) { p.Name = name; }
B. public Person UpdateName(Person p, string name) { p.Name = name; return p; }
C. public static Person UpdateName(this Person p, string name) { p.Name = name; return p; }
D. public static Person UpdateName(Person p, string name) { p.Name = name; return p; }
Solution
Step 1: Identify extension method syntax
Extension methods must be static, inside static classes, and the first parameter uses this keyword to specify the extended type.
Step 2: Check return type for fluent chaining
To enable chaining, the method must return the same object. public static Person UpdateName(this Person p, string name) { p.Name = name; return p; } returns Person and uses this Person p correctly.
Final Answer:
public static Person UpdateName(this Person p, string name) { p.Name = name; return p; } -> Option C
Quick Check:
Extension method + return self = public static Person UpdateName(this Person p, string name) { p.Name = name; return p; } [OK]
Hint: Extension methods are static with 'this' on first parameter [OK]
Common Mistakes:
Omitting 'static' keyword on method
Not using 'this' keyword on first parameter
Returning void instead of the object for chaining
3. Given the following code, what is the output?
public class Person {
public string Name { get; set; }
}
public static class PersonExtensions {
public static Person SetName(this Person p, string name) {
p.Name = name;
return p;
}
public static Person PrintName(this Person p) {
Console.WriteLine(p.Name);
return p;
}
}
var person = new Person();
person.SetName("Alice").PrintName();
medium
A. Alice
B. SetName
C. Compilation error
D. No output
Solution
Step 1: Understand method chaining
The SetName extension sets the Name property and returns the same Person object. Then PrintName prints the Name and returns the object.
Step 2: Trace output
Since SetName("Alice") sets Name to "Alice", PrintName() prints "Alice" to the console.
Final Answer:
Alice -> Option A
Quick Check:
Chained methods print 'Alice' [OK]
Hint: Chained methods return object, so output is printed value [OK]
Common Mistakes:
Expecting method names as output
Thinking chaining causes compile error
Assuming no output without explicit print
4. Identify the error in this extension method that aims to enable fluent chaining:
public static class StringExtensions {
public static string AppendExclamation(string s) {
s += "!";
return s;
}
}
medium
A. Missing 'this' keyword on the first parameter to make it an extension method
B. Method should return void for chaining
C. Cannot extend string type with extension methods
D. Method should be non-static
Solution
Step 1: Check extension method syntax
Extension methods require the first parameter to have the this keyword to specify the type being extended.
Step 2: Identify missing 'this'
The method parameter string s lacks this, so it is a normal static method, not an extension method.
Final Answer:
Missing 'this' keyword on the first parameter to make it an extension method -> Option A
Quick Check:
Extension method needs 'this' on first parameter [OK]
Hint: Extension methods always have 'this' on first parameter [OK]
Common Mistakes:
Forgetting 'this' keyword
Returning void instead of the object or string
Thinking string cannot be extended
5. You want to create a fluent interface to build a SQL query string using extension methods on string. Which approach correctly supports chaining multiple calls like "SELECT *".AddWhere("Age > 30").AddOrderBy("Name")?
hard
A. Each extension method modifies the original string in place and returns void
B. Each extension method takes this string query, appends the clause, and returns the new string
C. Each extension method returns a new object type instead of string
D. Extension methods cannot be used on string for fluent interfaces
Solution
Step 1: Understand string immutability
Strings in C# are immutable, so methods cannot modify the original string but must return a new string with changes.
To chain calls, each method must return the updated string. Each extension method takes this string query, appends the clause, and returns the new string after appending clauses.
Final Answer:
Each extension method takes this string query, appends the clause, and returns the new string -> Option B
Quick Check:
Immutable string + return new string = Each extension method takes this string query, appends the clause, and returns the new string [OK]
Hint: Strings are immutable; return new string for chaining [OK]
Common Mistakes:
Trying to modify string in place
Returning void breaks chaining
Assuming extension methods can't extend string
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.