When assigning a variable to another variable (or by passing it as a parameter to a method) either a copy of the value is created (in the case of Value types) or a reference to the original value is created (in the case of Reference types).
The ref
keyword allows you to instead create a reference to the original variable. This means that you can change what the original variable itself points to however this was only available when passing the variable to a method.
In C# 7.0 you can now create a local variable that is a reference to another variable allowing you to effectively change the contents of both by prefixing the variable declaration with ref
.
WARNING
Using ref
can lead to unexpected side effects and code that is hard to follow and debug. It should be used sparingly when measured performance requirements and gains require that trade-off.
Code
var greeting = "Hello, World!";
// Can take a reference to the string
ref var access = ref greeting;
// Can modify it via the reference variable
access = "Goodbye, World!";
Console.WriteLine(greeting); // Outputs "Goodbye, World!"
// Or change what the reference variable points to
var alternative = "Howdy Partner!";
access = ref alternative;
// Wrap the string in a class so we can change it from other variables
var greeting = new Wrapper("Hello, World!");
var access = greeting;
// Can modify it via the reference variable
access.Value = "Goodbye, World!";
Console.WriteLine(greeting.Value); // Outputs "Goodbye, World!"
// Or change what our 'reference' points to
access = new Wrapper("Howdy Partner!");
Notes
- The
ref
keyword shares some similarities with pointers in C and C++ - You can prefix
ref
withscoped
to restrict the lifetime of the value