Lesson 8.4

How to use Array as Parameter in C# with programming Example


Objective

What is Params array?
Usage of Params Array in C#.
Programming Example

What is Params Array?

Params array is a way to pass number as parameter to a method. Suppose you are creating a method in which you are not sure how much number can be passed as parameter at runtime. This method can be a simple method which accepts number as parameter and return addition of all those number. Only condition is that you are not sure how many numbers can be passed.

For example
public static int Add(22,53,98,23)
Or ,
public static int Add(98,53)
Or
public void Add(98,64,74,89,23,64,66,23,56)

How to Declare Params?

You can declare params parameter as follow:

Method_name(params int[] arr)

So you can see here that a method is accepting n number of parameter and returns addition of all those number. Using the Params Array you can handle this situation easily.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace params_array
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Add of 2,3,5,6,2,3 is " + Add(2, 3, 5, 6, 2, 3));
            Console.WriteLine("Add of 23,543,63,11 is " + Add(23, 543, 63, 11));
            Console.ReadKey();
        }
        public static int Add(params int[] arr)
        {
            int result = 0;
            foreach (int i in arr)
            {
                result += i;
            }
            return result;
        }
    }
}


Output

Add of 2,3,5,6,2,3 is 21
Add of 23,543,63,11 is 640
__

Explanation

What we did in this program

  1. Created a static method public static int Add(params int[] arr) which can accept n number of parameter.
  2. Using the foreach loop picked value from arr Params array into I and added all in result variable.
  3. Return result variable to function in main method.
  4. In main method we have used Add() method 2 times with different numbers of parameters and it returned sum of all values.
BackNext