简体   繁体   中英

When to return 'this' instead of 'void' in a method and why?

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.

Returning this is using a fluent interface design, that is a special case of method chaining when the return type is of the current object on which we are applying the method.

Method chaining is also the root of functional programming .

It is extensively used by Linq extension methods with IEnumerable<> and IQueryable<> .

It allows to call methods on the same object in a chained manner without repeating a variable name for each method call.

Therefore, this produces a shorter, cleaner and more maintainable code with fewer sources of errors.

So we use this when we want or need that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM