Usage of params modifier in C#

Lets see how to use params modifier in C#. The perfect example is Calculator implementation. ‘params’ access modifier when used on a method argument, allows it to accept multiple argument values. Lets see the simple Calculator implementation below. As you can see, method argument ‘numbers’ is defined as integer array and being called out by ‘params’ modified that allows it to accept more than one value.

class Calculator
   {
       public int Add(params int[] numbers)
       {
           var sum = 0;
 
           foreach (var i in numbers)
           {
               sum += i;
           }
           return sum;        
       }
   }

class PointProgram
    {
        public static void Main(string[] argvs)
        {
 
            var Calculator = new Calculator();
 
            Console.WriteLine("Sum is {0}", Calculator.Add(24344512));
 
 
        }
    }

Add a Comment

Your email address will not be published. Required fields are marked *