C# Tutorials - Herong's Tutorial Examples - v3.32, by Herong Yang
Types of Method Parameters
This section describes types of method parameters: value parameter, reference parameter, and output parameter.
A value parameter is a parameter by which a value will be passed from the caller into the called method. New value can be assigned to a value parameter, but this value will not be returned to the caller at the end of the call. Parameters of value based types are value parameters by default. Parameters of reference based types can not be declared as value parameters.
A reference parameter is a parameter by which a reference will be passed from the caller into the called method. The value referred by the parameter in the caller can be used in the called method. If a new value is assigned to a reference parameter in the called method, that value will replace the old value in the caller referred by the parameter. Parameters of reference based types are reference parameters by default. Parameters of value based types can be declared as reference parameters using the "ref" modifier.
An output parameter is a parameter by which the new value assigned in the called method will be returned to the caller and the old value referred in the caller will be replaced. However, at the time of entering the called method, values in the caller referred by the output parameters will not be transferred in the called method. Output parameters must be declared using the "out" modifier.
Let's play with different kinds of parameters in the following program:
// Parameters.cs // Copyright (c) 2008 HerongYang.com. All Rights Reserved. using System; class Parameters { static void Main() { int v, r, o; string s; v = 1; s = "1"; r = 1; o = 1; MyMethod(v, s, ref r, out o); Console.WriteLine("After calling: v = {0}",v); Console.WriteLine("After calling: s = {0}",s); Console.WriteLine("After calling: r = {0}",r); Console.WriteLine("After calling: o = {0}",o); } static void MyMethod(int v, string s, ref int r, out int o) { Console.WriteLine("In method: v = {0}",v); Console.WriteLine("In method: s = {0}",s); Console.WriteLine("In method: r = {0}",r); // Console.WriteLine("In method: o = {0}",o); // o is undefined v = 2; s = "2"; r = 2; o = 2; } }
Output:
In method: v = 1 In method: s = 1 In method: r = 1 After calling: v = 1 After calling: s = 1 After calling: r = 2 After calling: o = 2
I thought "string" is a reference type by default. But I was wrong. This program shows that a "string" parameter is a value parameter.
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