dotnet / csharplang

The official repo for the design of the C# programming language
11.54k stars 1.03k forks source link

Proposal: 'this' as return type #2559

Closed sliekens closed 5 years ago

sliekens commented 5 years ago

This is my first proposal so please go easy on me. :-)

It would be cool if we could use this as the return type for instance methods, to indicate that the method returns its containing object.

Use cases include builder objects and other fluent APIs.

public class PizzaBuilder {
    private string _dough;
    private string _sauce;
    private string _topping;

    public this UseDough(string dough) => _dough = dough;

    public this UseSauce(string sauce) => _sauce = sauce;

    public this UseTopping(string topping) => _topping = topping;

    public Pizza Build() {
        return new Pizza(_dough, _sauce, _topping);
    }
}

It would be synonymous for the following:

public class PizzaBuilder {
    private string _dough;
    private string _sauce;
    private string _topping;

    public PizzaBuilder UseDough(string dough) {
        _dough = dough; 
        return this;
    }
    public PizzaBuilder UseSauce(string sauce) {
        _sauce = sauce; 
        return this;
    }
    public PizzaBuilder UseTopping(string topping) {
        _topping = topping;
        return this;
    }

    public Pizza Build() {
        return new Pizza(_dough, _sauce, _topping);
    }
}
orthoxerox commented 5 years ago

Thank you for your interest in C# design!

I think there multiple issues requesting this feature already, so if you could repost your approach to the one with the most :+1:s it would be great.

jnm2 commented 5 years ago

Duplicate of https://github.com/dotnet/csharplang/issues/252 and https://github.com/dotnet/csharplang/issues/902.