Quantcast
Channel: source code bean » C#
Viewing all articles
Browse latest Browse all 10

Reference types are always passed by value in C#

$
0
0

Last week i had a discussion with a friend about C# and passing parameters to methods. My friend asked why it is possible to use the ‘ref’ keyword for a reference type in C# when passing it to a method, he was under the impression that reference types are passed by reference to methods. This seems to be a quite common misunderstanding about C#, to make it clear:

Reference types are always passed to methods by value (unless you use the ‘ref’ keyword)

What happens when you call a method with a reference type as parameter is that the value of the reference (the pointer, an address to pointing to the referenced object) is passed to the method (by value). What this means is that you can not modify the original reference, but you can modify the object it is referencing (pointing to).

By using the ‘ref’ keyword you will pass the address of the reference to the method, which means that you can modify its value.

This is a short example illustrating this (remember, in C#, a string is a reference type):

  1.  
  2. class Program
  3. {
  4.     static void Main(string[] args)
  5.     {
  6.         string s = "orig value";
  7.         Console.WriteLine("Orig value: " + s);
  8.            
  9.         MyFunc1(s);
  10.         Console.WriteLine("After MyFunc1: " + s);
  11.  
  12.         MyFunc2(ref s);
  13.         Console.WriteLine("After MyFunc2: " + s);
  14.     }
  15.  
  16.     public static void MyFunc1(string s)
  17.     {
  18.         s = "new value 1";
  19.     }
  20.  
  21.     public static void MyFunc2(ref string s)
  22.     {
  23.         s = "new value 2";
  24.     }
  25. }
  26.  

Output:
Orig value: orig value
After MyFunc1: orig value
After MyFunc2: new value 2


Viewing all articles
Browse latest Browse all 10

Trending Articles