Skip to content

Instantly share code, notes, and snippets.

@rleopold
Last active August 29, 2015 14:05
Show Gist options
  • Save rleopold/8e654cb89eadee0ecad5 to your computer and use it in GitHub Desktop.
Save rleopold/8e654cb89eadee0ecad5 to your computer and use it in GitHub Desktop.
example of ref keyword in C#
// 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