C# params parameters

Description

The params parameter modifier is used on the last parameter of a method so that the method accepts any number of parameters of a particular type.

The parameter type must be declared as an array.

Syntax

methodName(params type[] parameterName);

Example

For example:


using System;/*from w ww. j a  v a  2 s  .  c o m*/

class Program
{
    static void output(params int[] intPara)
    {
        for (int i = 0; i < intPara.Length; i++)
        {
            Console.WriteLine("params:" + intPara[i]);
        }
    }
    static void Main(string[] args)
    {
        output(1, 2, 3);
        output(1, 2, 3, 4, 5, 6);
    }
}

The output:

You can also supply a params argument as an ordinary array. The first line in Main is semantically equivalent to this:

output (new int[] { 1, 2, 3 } );

Example 2

The params type parameter must be the last parameter in that method.


using System;//from   w  ww. j  a va2s.c o  m

class Program
{
    static void output(int j, params int[] intPara)
    {
        Console.WriteLine("j:" + j);

        for (int i = 0; i < intPara.Length; i++)
        {
            Console.WriteLine("params:" + intPara[i]);
        }
    }

    static void Main(string[] args)
    {

        output(999, new int[] { 1, 2, 3 });
    }
}

The output:





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor