Params keyword in C#

In this article we can learn about Params keyword in C#.
  • 5622

Introduction

The concept of params keyword is very simple in C#. Params keyword is used to handle the situation where you want to create a method that receive n number of parameters at run time. The params keyword create an array that receive n number of parameter. This declaration takes the following form

static int Add(params int[] addNumbers)

params int[] addNumbers

params is keyword that creat an array  of int type .

In this line addNumbers variable can holds n number of parameters at runtime because it is declared with params keyword.

Example

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection;

class Program

{

    static void Main(string[] args)

    {

        //Passed 7 different values.

        int y = Add(1, 2, 3, 4, 5, 6, 7);

        Console.WriteLine("The Addition of  Numbers are : " + y);

        Console.ReadLine();

    }

    //Created a addNumbers variable as declared as Params.

    static int Add(params int[] addNumbers)

    {

        int Sum = 0;

        foreach (int i in addNumbers)

        {

            Sum = i + Sum;

        }

        return Sum;

    }

}

 

The output of following program

Clipboard200.jpg

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.