#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)

        public void BarkPlaylist(List<string> barkList)
            foreach (string s in barkList)

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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #838 – Object and Collection Initializers as Parameters

  1. tisch says:

    What i find more interesting is if you can pass parameters to a method which are used as source for a collection initializer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: