C# ref parameter

In this chapter you will learn:

  1. What is ref parameter
  2. How to create ref parameter
  3. Example for ref parameter
  4. Example to swap two values with ref parameter
  5. Note for ref parameter
  6. 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:

  1. What is an out parameter
  2. How to create an out parameter
  3. Example for out parameter
  4. Use out for reference type
  5. Note for out parameter
Home »
  C# Tutorial »
    C# Types »
      C# Method
C# class method
C# method parameters
C# ref parameter
C# out parameter
C# named parameters
C# params parameters
C# Optional parameters
C# method overloading
Recursive methods
C# Return Statement
static method
C# Main Function
C# Extension Methods