+92 332 4229 857 99ProjectIdeas@Gmail.com

"params" keyword (C#.net)




"params" keyword (C#.net):
The following code shows you how "params" keyword works. You can pass as much as arguments in the function that you want. you dont have to overload a function just use this keyword and pass arguments as much as you can.

Code
 
// Function returns the sum of numbers
public int paramsUse(params int[] list)
{
    int sum = 0;
    for (int i = 0; i < list.Length; i++)
    {
        sum += list[i];
    }

  return sum;
}

public static void Main(string[] args)
{

  int result = paramsUse(1, 2, 3, 4, 5); //Passing 5 arguments

  Console.WriteLine("The result of paramsUse function is : " + result);

  int result2 = paramsUse(1, 2, 3, 4, 5, 10, 19); //Passing 7 arguments

  Console.WriteLine("The result of paramsUse function is : " + result2);
}

Output of the program is:
The result of paramsUse function is : 15 
The result of paramsUse function is : 44


But , if modified the function to be like this:

// Function returns the sum of numbers
public int paramsUse(int[] list)
{
    int sum = 0;
    for (int i = 0; i < list.Length; i++)
    {
        sum += list[i];
    }

  return sum;
}

Then when passing arguments to this function you have to pass an array of integers values. See below 

public static void Main(string[] args)
{

  int result = paramsUse(new int[] {1, 2, 3, 4, 5 }); //Passing 5 arguments

  Console.WriteLine("The result of paramsUse function is : " + result);

  int result2 = paramsUse(new int[] {1, 2, 3, 4, 5, 10, 19 }); //Passing 7 arguments

  Console.WriteLine("The result of paramsUse function is : " + result2);
}

Output of the program is:
The result of paramsUse function is : 15 
The result of paramsUse function is : 44

0 comments: