Friday, April 30, 2021

C# params keyword in Method argument as modifier

UNDERSTAND THE ROLE OF params KEYWORD


using System;

namespace Console_params_keyword
{
    class Program
    {
        //params parameter must be one dimension array
        double Sum(params double[] values)
        {
            double result=0.0;
            for (int i = 0; i < values.Length; i++)
            {
                result += values[i];
            }
            return result;
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            //4 args
            Console.WriteLine(p.Sum(92, 1, 98, 3));
            Console.WriteLine(p.Sum(92.1, 98.3));
            //2 args two-digit decimal formatting using ToString()
            Console.WriteLine(p.Sum(92.1, 98.3).ToString("#.##"));
            Console.WriteLine(p.Sum(92.1, 98.3).ToString("#.00"));
        }
    }
}
OUTPUT
  • 194
  • 190.39999999999998
  • 190.4
  • 190.40

No comments:

Post a Comment

Hot Topics