What is the output of this C# code using a fluent interface?
public class Builder { private string text = ""; public Builder AddHello() { text += "Hello"; return this; } public Builder AddSpace() { text += " "; return this; } public Builder AddWorld() { text += "World"; return this; } public override string ToString() => text; } var result = new Builder().AddHello().AddSpace().AddWorld().ToString(); System.Console.WriteLine(result);
Look at how spaces are added in the chain.
The methods AddHello, AddSpace, and AddWorld add strings and return the same object, allowing chaining. The space is added explicitly by AddSpace, so the output is "Hello World" exactly.
Why are extension methods useful when building fluent interfaces in C#?
Think about how you can add methods to a class you cannot change.
Extension methods let you add new methods to existing classes, enabling fluent chaining without changing the original class code.
What error will this code cause when compiling?
public static class BuilderExtensions {
public static Builder AddExclamation(this Builder builder) {
builder.ToString() += "!";
return builder;
}
}Consider what ToString() returns and if it can be assigned to.
ToString() returns a string value, which is immutable and cannot be assigned to. The code tries to append "!" to the result of ToString(), which is invalid.
Which option shows the correct syntax for a fluent extension method that adds a period at the end of the Builder text?
Remember extension methods must be static and inside static classes.
Extension methods must be static methods inside static classes, with the first parameter preceded by 'this'. The method should return the builder to allow chaining.
Given the following code, what is the final output?
public class Builder {
private string text = "Start";
public Builder Append(string s) {
text += s;
return this;
}
public override string ToString() => text;
}
public static class BuilderExtensions {
public static Builder AddDash(this Builder b) => b.Append("-");
public static Builder AddStar(this Builder b) => b.Append("*");
public static Builder AddPlus(this Builder b) => b.Append("+");
}
var result = new Builder()
.AddDash()
.AddStar()
.AddPlus()
.AddDash()
.ToString();
System.Console.WriteLine(result);Follow the chain step by step, appending each symbol in order.
The Builder starts with "Start". Each extension method appends its symbol in the order called: AddDash adds '-', AddStar adds '*', AddPlus adds '+', then AddDash adds '-' again. So the final string is "Start-*+-".