Search Forum
(53671 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


 
Printable Version

Using Params Keyword
By Sriram Vaideeswaran

Sometimes we may require a variable number of arguments to be passed to a function. For example we may require a sum function which calculates the total of the numbers passed to it no matter how many numbers are passed.

In C# we can use the Params keyword and pass variable no of arguments to a function. It's much like using ParamArray in VisualBasic language. The syntax of params arguments is:
params datatype[] argument name

Note that the argument passed using params argument should be an single dimension array also it should be the last argument in the argument list for the function.

The params parmeter can then be accessed as an normal array.

Example

class ParamsTest
{
    static void Main()
    {
         System.Console.WriteLine(sum(2,3,4)); // Three Arguments Passed
         System.Console.WriteLine(sum(10,20,30,40,50,60));//Six Arguments
    }
    static int sum(params int[] num)
    {
         int tot=0;
         foreach(int i in num)
         {
              tot=tot+i;
         }
         return tot;
    }
}