One can create a method that displays any number of integers to the console by passing in an array of integers and then iterating over the array with a foreach loop. The params keyword allows you to pass in a variable number of parameters without necessarily explicitly creating the array.
In the next example, we will create a method, DisplayVals(), that takes a variable number of integer arguments:
public void DisplayVals(params int[] intVals)
The method itself can treat the array as if an integer array were explicitly created and passed in as a parameter. We are free to iterate over the array as you would over any other array of integers:
foreach (int i in intVals)
{
Console.WriteLine(“DisplayVals {0}”,i);
}
The calling method, however, need not explicitly create an array: it can simply pass in integers, and the compiler will assemble the parameters into an array for the DisplayVals( ) method:
t.DisplayVals(5,6,7,8);
We are free to pass in an array if you prefer:
int [] explicitArray = new int[5] {1,2,3,4,5};
t.DisplayVals(explicitArray);
This example provides the complete source code illustrating the params keyword.
using System;
using System.Collections.Generic;
using System.Text;
namespace UsingParams
{
public class Tester
{
static void Main( )
{
Tester t = new Tester( );
t.DisplayVals(5,6,7,8);
int [] explicitArray = new int[5] {1,2,3,4,5};
t.DisplayVals(explicitArray);
}
public void DisplayVals(params int[] intVals)
{
foreach (int i in intVals){
Console.WriteLine(“DisplayVals {0}”,i);
}
}
}
}
Output:
DisplayVals 5
DisplayVals 6
DisplayVals 7
DisplayVals 8
DisplayVals 1
DisplayVals 2
DisplayVals 3
DisplayVals 4
DisplayVals 5
Thanks
(Faisal Sikder)
sidharthan
February 23, 2012 at 8:33 am
I execute this program.This output is wrong.Please explain correct program explanation
sidharthan
February 23, 2012 at 8:36 am
The Output comes only 5 6 78 only
Faisal Sikder
February 24, 2012 at 12:12 am
Hello Sidharthan
Thanks for comment.
I have tested it ri8 now and got the right answer. I am little bit confused, where is the problem ?? Its a very straightforward code, it should work.
If you only get 5 6 7 8 then your second ” t.DisplayVals(explicitArray) ” is not working. please try to debug why its not calling.
Faisal
megass
February 25, 2013 at 2:03 am
Hello, I enjoy reading all of your post. I like to write a little comment to support
you.