What are the benefits (or drawbacks) of returning a reference to 'this' object in a method that modifies itself? When should returning a 'this' be used as apposed to void?
When looking at an answer on code review stack exchange, I noticed that the answer used a 'return this' in a self operating method.
Simplified class from original:
class Item
{
public Item(string name)
{
Name = name;
}
public string Name { get; private set; }
public Item AddComponent(ItemComponent component)
{
_components.Add(component);
return this;
}
private List<ItemComponent> _components = new List<ItemComponent>();
}
Consuming code simplified:
var fireSword = new Item("Lightbringer")
.AddComponent(new Valuable { Cost = 1000 })
.AddComponent(new PhysicalDamage { Slashing = 10 });
Related question seems to have conflicting answers by different users.
This question is also similar with the answer referencing fluent interfaces to use in object creation.