.comment-link {margin-left:.6em;}
My Photo
Name:
Location: Unspecified, Mauritius

I too, am a bug within Māyā.

My Other Blog(s) and Site(s)
Friend sites and blogs
My Recent Posts
Tutorials
Best Articles
My C-Sharp Ideas
Archives
Blog Directories

Friday, July 22, 2005

 

Yet another cool and useful feature

The Params keyword
[Beginner]


The params keyword could be one of the coolest features of C-Sharp, if you haven't heard of it yet. Simply put, it allows you to enter multiple parameters of a same type. An alternative to this could be the use of an array - i.e. create a method that accepts an array of a certain kind of objects, but that's really troublesome. Here, check the code out - it's pretty simple and straightforward:




using System;

namespace MultiParams
{
/// <summary>
/// MultiParam App
/// </summary>
class MyClass
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine(AddAll(43, 94, 29, 958, 3283, 9285).ToString());
Console.ReadLine();
}

public static double AddAll(params int[] numbers)
{
double total = 0;

foreach(int i in numbers)
{
total += i;
}

return total;
}
}
}


What really interests us is the AddAll method. Let's have a closer look:



public static double AddAll(params int[] numbers)
{
double total = 0;

foreach(int i in numbers)
{
total += i;
}

return total;
}



There's nothing particular in that method, apart from the "params" keyword used in the parameters. It's pretty strightforward. The use of the params in the parameters allows users to pass multiple values (in this case, multiple int's) of the same type - they all get kicked into an array of that object type (in this example, an array of int, which I named "numbers"). Using this function gets really easy now. All you have to do is to call the AddAll method with as much number of integer parameters as you want! Et voilà! Rien de plus façile! I called the AddAll method, and passed in a few numbers - and called the ToString() method.

Now, think of your own ways to make a good use of the params keyword ;)