Params modifier example

CGN007
Posted by CGN007 under C# category on | Points: 40 | Views : 915
1.ParamsDemo class containing a method Sum() that uses params array as parameter

public class ParamsDemo
{
//Function to calculate the sum.
//Params array is used as parameter
public int Sum(params int[] nums)
{
int total = 0;
if (nums.Length == 0)
{
Console.WriteLine("No arguments.");
return 0;
}
for (int i = 0; i < nums.Length; i++)
total = total + nums[i];
return total;
}
}


2.Calling the method inside the main()
 class Program
{
static void Main(string[] args)
{
//Creating the object of ParamsDemo
ParamsDemo paramsObj = new ParamsDemo();
//Adding two numbers
Console.WriteLine(paramsObj.sum(1, 3));
//Adding three numbers
Console.WriteLine(paramsObj.sum(1, 3, 5));
Console.ReadKey();
}
}

Comments or Responses

Login to post response