Param Keyword in C#

By using the params keyword, you can specify a method parameter that takes a variable number of arguments.You can send a comma-separated list of arguments of the type specified in the parameter declaration or an array of arguments of the specified type. You also can send no arguments. If you send no arguments, the length of the params list is zero.

No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

 Example: 
Write the below code in a console application.

  1. class Program  
  2. {  
  3.     static void Main(string[] args)   
  4.     {  
  5.         int y = Add(10, 20);  
  6.         Console.WriteLine(y);  
  7.         Console.ReadLine();  
  8.     }  
  9.   
  10.     public static int Add(params int[] MyColl)   
  11.     {  
  12.         int total = 0;  
  13.   
  14.         foreach(int i in MyColl)   
  15.         {  
  16.             total += i;  
  17.         }  
  18.         return total;  
  19.     }  
  20. }  
Output



Let us now add few more parameter and see how the result looks like. In the following program I have added three extra arguments.
  1. class Program   
  2. {  
  3.     static void Main(string[] args)   
  4.     {  
  5.         int y = Add(10, 20, 30, 40, 50);  
  6.         Console.WriteLine(y);  
  7.         Console.ReadLine();  
  8.     }  
  9.   
  10.     public static int Add(params int[] MyColl)  
  11.     {  
  12.         int total = 0;  
  13.   
  14.         foreach(int i in MyColl)   
  15.         {  
  16.             total += i;  
  17.         }  
  18.         return total;  
  19.     }  
  20. }  
Following is the output.

 

Ebook Download
View all
FileInfo in C#
Read by 9.7k people
Download Now!
Learn
View all