C# ref parameter

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 ww .j a va2 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.

Example 2

The ref modifier is essential in implementing a swap method:


using System;// w ww .  j  a va  2 s  .c  o 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;//from   www  . jav  a 2s . co  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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor