Posts Tagged ‘C#2.0’

C# function parameters passing

March 24th, 2009 Comments off

Yes, C# doesn’t support variable number of parameters in function signature,
by default, according to MSDN, the parameters passed by value:

A parameter declared with no modifiers is a value parameter. A value parameter corresponds to a local variable that gets its initial value from the corresponding argument supplied in the method invocation.

But there is something more interesting than that:

ref keyword: pass the value of the parameter into the function body by reference.

void addme(ref int i){
...... in some function body..
i = 10;
Console.WriteLine(i); /// output 11;

out keyword: sometimes a single retrurn is not enough; why not use the input parameter as return value container? the parameter specifies with out keyword doen’t need to be initialize.
params keyword: A parameter declared with a params modifier is a parameter array. If a formal parameter list includes a parameter array, it must be the last parameter in the list and it must be of a single-dimensional array type. For example, the types string[] and string[][] can be used as the type of a parameter array, but the type string[,] cannot. It is not possible to combine the params modifier with the modifiers ref and out.

using System;
class Test
static void F(params int[] args) {
Console.Write(”Array contains {0} elements:”, args.Length);
foreach (int i in args)
Console.Write(” {0}”, i);
static void Main() {
int[] arr = {1, 2, 3};
F(10, 20, 30, 40);

Output is
Array contains 3 elements: 1 2 3
Array contains 4 elements: 10 20 30 40
Array contains 0 elements:
For details you can refer to MSDN document HERE

Categories: C#, Tech Tags: , ,