#262 – Passing Data to a Method Using Parameters
March 6, 2011 Leave a comment
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.