Bird
0
0

How can you use the this keyword to implement a fluent interface in C#? Consider this method:

hard🚀 Application Q9 of 15
C Sharp (C#) - Classes and Objects
How can you use the this keyword to implement a fluent interface in C#? Consider this method:
public class Builder {
  private string result = "";
  public Builder Add(string text) {
    result += text;
    // What to return here?
  }
}
AReturn <code>this</code> to allow method chaining
BReturn <code>void</code> to stop chaining
CReturn a new Builder instance
DReturn <code>null</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand fluent interface pattern

    Fluent interfaces return the current object to allow chaining multiple method calls.
  2. Step 2: Use this to return current instance

    Returning this allows calls like builder.Add("a").Add("b").
  3. Final Answer:

    Return this to allow method chaining -> Option A
  4. Quick Check:

    Return this for fluent method chaining [OK]
Quick Trick: Return this to chain methods fluently [OK]
Common Mistakes:
MISTAKES
  • Returning void breaks chaining
  • Returning new instance loses state
  • Returning null causes runtime errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes