Search code examples
c#oopreturnthisfluent

Is it bad practice for a class method to return `this`?


public class Chain
{
    public string ChainString;

    public Chain() 
    {
        ChainString = "{}"; 
    }

    public Chain AddLink()
    {
        ChainString += "-{}";
        return this; // is this a bad idea?
    }
}

In the above example, the AddLink method returns the this. The reason I want to do this is for a more readable instantiation, like below.

// more verbose (here, `AddLink` returns void)
Chain myChain = new Chain();
myChain.AddLink();
myChain.AddLink();
myChain.AddLink();
// myChain.ChainString = "{}-{}-{}-{}"
// nicer
Chain myChain = new Chain()
    .AddLink()
    .AddLink()
    .AddLink();
// myChain.ChainString = "{}-{}-{}-{}"

Is there any reason I shouldn't do this? I can't think of any, but it feels a bit hacky and I've not seen it done elsewhere.


Solution

  • No. This is a common pattern for fluent interfaces.