C# Params Array

In this chapter you will learn:
  • What is param array in C#?
  • What is the advantage of using param array?
  • How to use param array in C# programming?

Sometimes, you are not assured about a number of parameters or you want to create a method that can accept n number of parameters at runtime. This situation can be handled with params type array in C#. The params keyword creates an array at runtime that receives and holds n number of parameters.

static int add(params int[] allnumber)

In the preceding line, the allnumber variable can holds n number of parameters at runtime because it is declared with params keyword.

Programming Example of Params Array in C#

In this example, we are creating a function add() that will receive any number of integer parameters at runtime and returns the sum of all those numbers. We will use params array to achieve this goal in C#.

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

namespace params_array
{
    class Program
    {
        static int add(params int[] allnumber)
        {
            int sum = 0;
            foreach (int n in allnumber)
            {
                sum = sum + n;
            }
            return sum;
        }
        static void Main(string[] args)
        {
            int sum;
            // passing three parameters
            sum = Program.add(1, 2, 3);
            Console.WriteLine("Sum of 1,2,3 is:\t{0}", sum);

            // passing five parameters
            sum = Program.add(3, 5, 2, 6, 2);
            Console.WriteLine("Sum of 3,5,2,6,2 is:\t{0}", sum);
            Console.ReadLine();
        }
    }
}

Output

Sum of 1,2,3 is:         6
Sum of 3,5,2,6,2 is:   18
__

Summary

In this chapter you learned about param array in C#. You also learned how to use param array in C# programming. In next chapter you will learn how to pass array as parameter.

More Examples

Write A Program To Print One Dimensional Array In Reverse Order
Write A Program To Sort One Dimensional Array In Descending Order Using Non Static Method.
Write A Program To Sort One Dimensional Array In Desending Order Static Class Array Method.
Write A Program To Sort One Dimensional Array In Ascending Order Using Non Static Method.
Write A Program To Sort One Dimensional Array In Ascending Order Using Static Method.
Write A Program To Add The Diagonal Of Two-Dimensional Array.

More Articles

 

Share your thought



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.