#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 software development and sailing.

One Response to #262 – Passing Data to a Method Using Parameters

  1. Pingback: #802 – A Method Might Have No Parameters | 2,000 Things You Should Know About C#

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: