I have actually no idea of what this is called in C#. But i want to add the functionallity to my class to add multiple items at the same time.
myObj.AddItem(mItem).AddItem(mItem2).AddItem(mItem3);
Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.
Method chaining is a technique in which methods are called on a sequence to form a chain and each of these methods return an instance of a class. These methods can then be chained together so that they form a single statement. A fluent interface is an object-oriented API that depends largely on method chaining.
Method chaining just means chaining multiple method calls into a single expression, rather than using multiple statements. Because the find method returns a different object from the click method. It also encourages people to write code that silently fails.
The technique you mention is called chainable methods. It is commonly used when creating DSLs or fluent interfaces in C#.
The typical pattern is to have your AddItem() method return an instance of the class (or interface) it is part of. This allows subsequent calls to be chained to it.
public MyCollection AddItem( MyItem item ) { // internal logic... return this; }
Some alternatives to method chaining, for adding items to a collection, include:
Using the params
syntax to allow multiple items to be passed to your method as an array. Useful when you want to hide the array creation and provide a variable argument syntax to your methods:
public void AddItems( params MyItem[] items ) { foreach( var item in items ) m_innerCollection.Add( item ); } // can be called with any number of arguments... coll.AddItems( first, second, third ); coll.AddItems( first, second, third, fourth, fifth );
Providing an overload of type IEnumerable or IEnumerable so that multiple items can be passed together to your collection class.
public void AddItems( IEnumerable<MyClass> items ) { foreach( var item in items ) m_innerCollection.Add( item ); }
Use .NET 3.5 collection initializer syntax. You class must provide a single parameter Add( item )
method, implement IEnumerable, and must have a default constructor (or you must call a specific constructor in the initialization statement). Then you can write:
var myColl = new MyCollection { first, second, third, ... };
Use this trick:
public class MyClass { private List<MyItem> _Items = new List<MyItem> (); public MyClass AddItem (MyItem item) { // Add the object if (item != null) _Items.Add (item) return this; } }
It returns the current instance which will allow you to chain method calls (thus adding multiple objects "at the same time".
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