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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: