ref parameters
In this chapter you will learn:
- Use ref to pass a value type by reference
- Swap two values
- Swap two references
- Change string using ref keyword
Pass integer by ref
To pass by reference we use the ref
parameter modifier.
We add the ref
modifier in front of the parameter.
The ref
parameter modifier causes C# to
create a call-by-reference, rather than a call-by-value.
using System;/*j av a 2 s .c o m*/
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.
The ref
keyword is required in the method
declaration as well as the method call.
From the output we can see that the int
value in
the main
method is changed by the method MyMethodRef
since the pointer to the int
value is passed into
the MyMethodRef
method.
Swap two values
We can use the ref parameter modifier to exchange value of two parameters.
using System; /*from j a v a2 s. c om*/
class Swap {
// This method now changes its arguments.
public void swap(ref int a, ref int b) {
int t;
t = a;
a = b;
b = t;
}
}
class MainClass {
public static void Main() {
Swap ob = new Swap();
int x = 10, y = 20;
Console.WriteLine("x and y before call: " + x + " " + y);
ob.swap(ref x, ref y);
Console.WriteLine("x and y after call: " + x + " " + y);
}
}
The code above generates the following result.
Use ref with reference types
We can use ref
modifier for reference type value as well.
using System;// ja v a 2 s . c om
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.
Change string using ref keyword
using System;/*from jav a 2 s .com*/
class MainClass
{
public static void UpperCaseThisString(ref string s)
{
s = s.ToUpper();
}
public static void Main()
{
string s = "str";
Console.WriteLine("-> Before: {0}", s);
UpperCaseThisString(ref s);
Console.WriteLine("-> After: {0}\n", s);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: