
.NET 1.1+C# Method Parameters (2)
The forty-sixth part of the C# Fundamentals tutorial expands upon the creation of methods described in the previous instalments. In this article, the various types of parameter that can be added to a method definition are described.
Reference Parameters
Passing Value Types by Reference
An alternative to passing parameters by value is passing by reference. When using reference parameters for value types a copy of the value is not made. Instead, the variable used in the parameter is itself passed to the called method. This makes the behaviour similar to using reference types in value parameters; any changes to the value of the parameter variable is also seen outside of the method.
A reference parameter is declared using the ref keyword before the parameter type. This prefix must also be used when calling the method.
The following sample code is based upon the first example in this article but by using a reference parameter rather than a value parameter, the results seen are different.
static void Main(string[] args)
{
int original = 100;
showDouble(ref original);
Console.WriteLine("Original: {0}", original);
}
static void showDouble(ref int valueToShow)
{
valueToShow *=2;
Console.WriteLine("Double: {0}", valueToShow);
}
/* OUTPUT
Double: 200
Original: 200
*/
Passing Reference Types by Reference
Reference type data can be passed to reference parameters. In this case, rather than passing a copy of the reference to the method, as when using value parameters, the reference variable itself is passed. In this situation, property changes within the method are visible outside of the method as expected. However, if the variable is reassigned within the method, the variable outside of the method is also reassigned.
We can demonstrate by modifying the earlier example relating to the Ball class. In the following code the ball is inflated as is was previously with the reference parameters showing no apparent difference in functionality. When the GetNewBall method is called, the ball variable is reassigned as a completely new object. This is mirrored in the Main method of the program also.
class Program
{
static void Main(string[] args)
{
Ball football = new Ball();
football.Diameter = 15;
InflateBall(ref football);
Console.WriteLine("Diameter: {0}", football.Diameter);
GetNewBall(ref football);
Console.WriteLine("Diameter: {0}", football.Diameter);
/* OUTPUT
Diameter: 16
Diameter: 1
*/
}
static void InflateBall(ref Ball ball)
{
ball.Diameter++;
}
static void GetNewBall(ref Ball ball)
{
ball = new Ball();
ball.Diameter = 1;
}
}
class Ball
{
private int _diameter;
public int Diameter
{
get
{
return _diameter;
}
set
{
_diameter = value;
}
}
}
5 August 2007