-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Closed
Description
Scenario
Today, to create a fluent API method, you have to:
- set the return type to the current class
- return this
But when you add inheritance to the mixture, it get not so fluent anymore.
What you do today:
class FluentBase
{
string _name;
public FluentBase WithName(string name) { _name = name; return this; }
}
class FluentSomething : FluentBase
{
}
FluentSomething a = ...;
FluentSomething b = a.WithName("Test"); // Build error
FluentSomething b = (FluentSomething)a.WithName("Test"); // Ok
There is nothing that ensures that your method will return the current instance (looking at the method signature), and the returned type is always the base class, not the instance type.
Proposal idea
To have something like
class FluentBase
{
string _name;
public this WithName(string name) { _name = name; }
}
The "this" return type would mean that the method returns the current instance type.
With that:
FluentSomething a = ...;
FluentSomething b = a.WithName("Test"); // Success
would compile, and no casts would be necessary.
Overriding the method would still work, and is would always return the current instance.
Advantages
- Simpler to write fluent methods (No return this necessary).
- Clearer API (no guessing about whether the method return a new instance, or itself).
- Better tooling (Intelissense would know more specifically the method return type).
This is the raw idea, not a formal proposition, in a new thread, to keep things organized.
Reactions are currently unavailable