#838 – Object and Collection Initializers as Parameters
May 7, 2013 1 Comment
You can use object and collection initializers to initialize an object or collection when it is declared. You can also use an object initializer anywhere that an instance of the corresponding object is expected. And you can use a collection initializer wherever an instance of the collection is expected.
This means that we can use initializers to create an object passed as a parameter to a method.
Suppose that we have the following methods defined in a Dog class:
public static void DoSomethingWithDog(Dog d) { d.Bark("Woof"); d.Fetch(); } public void BarkPlaylist(List<string> barkList) { foreach (string s in barkList) Bark(s); }
We can pass an object initializer that creates a new Dog instance to the DoSomethingWithDog method. And we can pass a collection initializer to the BarkPlaylist method.
// Object initializer as parameter Dog.DoSomethingWithDog(new Dog { Name = "Kirby", Age = 15 }); // Collection initializer as parameter myDog.BarkPlaylist(new List<string> { "Woof", "Growf", "Blurp" });