Params Keyword in C#

Params Keyword

In this blog we will learn Params 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.     public static int Add(params int[] MyColl)  
  10.     {  
  11.         int total = 0;  
  12.         foreach(int i in MyColl)  
  13.         {  
  14.             total += i;  
  15.         }  
  16.         return total;  
  17.     }  
  18. }  
Output
 
 


Ebook Download
View all
Learn
View all