#838 – Object and Collection Initializers as Parameters

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" });
Advertisement

#837 – Object Initializers within Collection Initializers

Recall that you can initialize a collection when it is declared, using a collection initializer.

            List<Dog> myDogs = new List<Dog>
            {
                new Dog("Kirby", 15),
                new Dog("Ruby", 3)
            };

Also recall that, instead of invoking a constructor, you can initialize an object by using an object initializer.

            Dog myDog = new Dog { Name = "Kirby", Age = 15 };

You can combine these techniques, using object initializers within collection initializers.

            List<Dog> myDogs = new List<Dog>
            {
                new Dog { Name = "Kirby", Age = 15 },
                new Dog { Name = "Ruby", Age = 3 }
            };