params keyword in C#

Hi all,

Have you ever used params keyword in your programs? It is a keyword used to pass various numbers of arguments to a method. You can pass the arguments as comma separated list to the methods that accepts its parameters with params keyword. Methods with params keyword and without params keyword are called in the program differently. For example:

static int sum1(params int [] values)
{
int total = 0;
foreach (int value in values)
{  total += value; }
return total;
}

static int sum 2(params int [] values)
{
int total = 0;
foreach (int value in values)
{  total += value; }
return total;
}

static void main()
{
int result1 = sum1(); // can be used with no parameters
int result2 = sum1(1);
int result3 = sum1(1, 3, 4);
int result4 = sum2(new int [] {1});
int result4 = sum2(new int [] {1, 2, 5, 6});
}

 

This entry was posted in Uncategorized. Bookmark the permalink.

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