The specified technique is called chain methods. It is commonly used when creating DSL or smooth interfaces in C #.
A typical template is for your AddItem () method to return an instance of the class (or interface) of which it is a part. This allows you to bind subsequent calls to it.
public MyCollection AddItem( MyItem item ) {
Some alternatives to the method chain for adding items to a collection include:
Using params syntax to allow multiple elements to be passed to your method as an array. Useful if you want to hide the creation of an array and provide the syntax of variable arguments to your methods:
public void AddItems( params MyItem[] items ) { foreach( var item in items ) m_innerCollection.Add( item ); }
Providing an overload of type IEnumerable or IEnumerable so that multiple elements can be passed along with your collection class.
public void AddItems( IEnumerable<MyClass> items ) { foreach( var item in items ) m_innerCollection.Add( item ); }
Use the .NET 3.5 collection initializer syntax. The class must provide a single parameter Add( item ) , 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, ... };
LBushkin Jul 13 '09 at 14:36 2009-07-13 14:36
source share