#772 – Initializing an Array as Part of a Method Call

When you want to pass an array to a method, you could first declare the array and then pass the array by name to the method.

Suppose that you have a Dog method that looks like this:

        public void DoBarks(string[] barkSounds)
        {
            foreach (string s in barkSounds)
                Console.WriteLine(s);
        }

You can declare the array and pass it to the method:

            Dog d = new Dog();

            // Declare array and then pass
            string[] set1 = { "Woof", "Rowf" };
            d.DoBarks(set1);

Or you can just initialize a new array instance as part of the method call, without first declaring it:

            // Initialize and pass array without declaring
            d.DoBarks(new string[] { "Grr", "Ack-ack" });

You can also initialize a multi-dimensional array as part of a method call:

            // Initialize and pass multi-dimensional array
            d.AddNumbers(new int[,] { { 1, 2, 3 }, { 9, 10, 11 }, { 100, 12, 32 } });

772-001

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.

2 Responses to #772 – Initializing an Array as Part of a Method Call

  1. Pingback: Dew Drop – February 4, 2012 (#1,493) | Alvin Ashcraft's Morning Dew

  2. Pingback: Dew Drop – February 6, 2013 (#1,494) | Alvin Ashcraft's Morning Dew

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: