C# ref parameter
In this chapter you will learn:
- What is ref parameter
- How to create ref parameter
- Example for ref parameter
- Example to swap two values with ref parameter
- Note for ref parameter
- Swap two references by Using ref with reference types
Description
Passing variables by value is the default, but you can force value parameters to be passed by reference.
To pass by reference , C# provides the ref parameter modifier.
Syntax
methodName(ref type parameterName){
}
when calling the method:
methodName(ref variableName);
Notice how the ref modifier is required both when writing and when calling the method. This makes it very clear what's going on.
Example 1
Example for ref parameter
using System;// w w w . ja v a 2 s . c om
class MainClass
{
static void Main(string[] args)
{
int MyInt = 5;
MyMethodRef(ref MyInt);
Console.WriteLine(MyInt);
}
static public int MyMethodRef(ref int myInt)
{
myInt = myInt + myInt;
return myInt;
}
}
The code above generates the following result.
Example 2
The ref
modifier is essential in implementing a swap method:
using System;/*w w w . jav a 2s . co m*/
class Test
{
static void Swap (ref string a, ref string b)
{
string temp = a;
a = b;
b = temp;
}
static void Main()
{
string x = "Penn";
string y = "Teller";
Swap (ref x, ref y);
Console.WriteLine (x); // Teller
Console.WriteLine (y); // Penn
}
}
The code above generates the following result.
Note
A parameter can be passed by reference or by value, regardless of whether the parameter type is a reference type or a value type.
Example 3
We can use ref
modifier for reference type value as well.
using System;//www .ja va 2s.c o m
class Rectangle
{
public int Width = 5;
public int Height = 5;
}
class Program
{
static void change(ref Rectangle r)
{
r = null;
}
static void Main(string[] args)
{
Rectangle r = new Rectangle();
Console.WriteLine(r.Width);
change(ref r);
Console.WriteLine(r == null);
}
}
The output:
If we use the ref
modifier in front of a reference
type what we get in the method is the address of the reference or
the reference of the reference.
Next chapter...
What you will learn in the next chapter:
- What is an out parameter
- How to create an out parameter
- Example for out parameter
- Use out for reference type
- Note for out parameter