C# Params Keyword

C# Code Snippets Params Keyword
Share:

About

In this code snippet, we will learn how to use the params keyword in C#.

The params keyword is used to define an array of input parameters for a method. Instead of explicitly defining every single one we can just pass in an array of parameters. As you can imagine when you have a lot of parameters this becomes very useful. 

Let’s see the code example below.

Code:

using System;

namespace Params
{
    class Program
    {
        static void Main(string[] args)
        {
            Add(5,10,20,1,7);

            Console.ReadLine();
        }

        //Params is used to define an array of input parameters. 
        //As you can imagine this would require a lot more work if every parameter would have to be defined. 
        //Also for every different number of parameters we would have to define a separate overloaded method.
        public static void Add(params int[] numbers)
        {
            int sum = 0;

            foreach (var item in numbers)
            {
                sum += item; 
            }

            Console.WriteLine(sum);
        }
    }
}

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger