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.
No. This is a common pattern for fluent interfaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With