Last active
August 29, 2015 14:05
-
-
Save rleopold/8e654cb89eadee0ecad5 to your computer and use it in GitHub Desktop.
example of ref keyword in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// LinqPad example of ref keyword in C# | |
// "in c# objects are always passed by reference" -- NOT TRUE!!! | |
// what actually happens is that references are always passed by value! | |
// using the ref keyword passes the reference explicitly | |
void Main() | |
{ | |
var s = new StringBuilder("hello"); | |
Console.WriteLine(s.ToString()); | |
SetNull(s); | |
Console.WriteLine(s == null); | |
SetNull(ref s); | |
Console.WriteLine(s == null); | |
} | |
public static void SetNull(StringBuilder x) | |
{ | |
x = null; //<-- this is a copy of the reference to s | |
} | |
public static void SetNull(ref StringBuilder x) | |
{ | |
x = null; //<-- this IS the reference to s | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment