#262 – Passing Data to a Method Using Parameters

You can pass one or more data values to a method using parameters.  A parameter in a method is just a variable, usable only within that method, that refers to a piece of data passed into the method.

Here’s an example of an instance method in a Dog class.  The Bark methods accepts a phrase for the dog to bark and the number of times that he should bark.  It then uses this data to do the barking.

        public void Bark(string barkPhrase, int numberBarks)
        {
            for (int i = 0; i < numberBarks; i++)
            {
                Console.WriteLine("{0} says: {1}", Name, barkPhrase);
            }
        }

We would call the Bark method on a Dog object as follows:

            Dog kirby = new Dog();
            kirby.Name = "Kirby";

            kirby.Bark("Wooferooni", 3);
            kirby.Bark("Rowf", 1);

And we’d get the following output:

The calling code invokes the method and passes a value for each parameter into the method.

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.

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers