C# Tutorials - Herong's Tutorial Examples - v3.32, by Herong Yang
Method Parameter Arrays
This section describes method parameter arrays, which can be used as the last parameter in method definition to take an undefined number of parameters.
A parameter array is a parameter by which an undefined number of parameters can be passed into the called method from the caller. A parameter array must be an array type with the "params" modifier. The caller can supply an array, one value, two values or any number of values for a parameter array. A parameter array must be the last parameter of a method.
The following program shows the differences between a normal array parameter and a special parameter array:
// ParameterArray.cs
// Copyright (c) 2008 HerongYang.com. All Rights Reserved.
using System;
class ParameterArray {
static void Main() {
int i1, i2;
int[] a = new int[2];
Console.WriteLine("Testing array parameter...");
i1 = 11;
i2 = 12;
a[0] = 11;
a[1] = 12;
AParameter(a);
// AParameter(i1, i2); //not allowed
Console.WriteLine("After calling: a[0] = {0}",a[0]);
Console.WriteLine("After calling: a[1] = {0}",a[1]);
Console.WriteLine("Testing parameter array...");
PArray(a);
PArray(i1,i2);
Console.WriteLine("After calling: a[0] = {0}",a[0]);
Console.WriteLine("After calling: a[1] = {0}",a[1]);
Console.WriteLine("After calling: i1 = {0}",i1);
Console.WriteLine("After calling: i2 = {0}",i2);
}
static void AParameter(int[] a) {
Console.WriteLine("In method: a[0] = {0}",a[0]);
Console.WriteLine("In method: a[1] = {0}",a[1]);
a[0] = 21;
a[1] = 22;
}
static void PArray(params int[] a) {
Console.WriteLine("In method: a[0] = {0}",a[0]);
Console.WriteLine("In method: a[1] = {0}",a[1]);
a[0] = 31;
a[1] = 32;
}
}
Output:
Testing array parameter... In method: a[0] = 11 In method: a[1] = 12 After calling: a[0] = 21 After calling: a[1] = 22 Testing parameter array... In method: a[0] = 21 In method: a[1] = 22 In method: a[0] = 11 In method: a[1] = 12 After calling: a[0] = 31 After calling: a[1] = 32 After calling: i1 = 11 After calling: i2 = 12
Note that if you are calling parameter array with an array, it will be used as a reference parameter. If you are calling parameter array with a list of elements, and the elements are value based types, they will be used a value parameters.
Table of Contents
Logical Expressions and Conditional Statements
►Passing Parameters to Methods
Visual C# 2010 Express Edition
C# Compiler and Intermediate Language
Compiling C# Source Code Files
MSBuild - Microsoft Build Engine
System.Diagnostics.FileVersionInfo Class
WPF - Windows Presentation Foundation