Jason Rowe

Be curious! Choose your own adventure.

C# 7.0 ref return values

A friend at work sent me this sarcastic message today “yoooooooo this C# 7.0 feature will SHOCK you”. After his code snippet and explanation I was thinking to myself, why oh why would they put something like this in C# 7. As we dug in a bit things became more clear but at first I just wanted to wash my eyes out and forget this feature exists. Turns out if you take a closer look there is a case that could be useful in the real world. That use case is not for mere mortals but still nice to know.

What is this new garbage?

A simple example of ref return values:

public class ExampleClass
{
  int number;
  public ref int GetNumber() => ref number;
  public void PrintNumber() => Console.WriteLine(number);
}

 // in code using 
ref int num = ref exampleClass.GetNumber();
num = 12345;
exampleClass.PrintNumber();
// prints 12345

If you are not familiar with C# before the addition of ref return values PrintNumber() would display zero. The int would be copied out of GetNumber and passed as a value type and could not be changed. More detail on reference types vs value types in C#. Why would they add something like this?

Why would they add this?

Eric Lippert give some background into the origin of this feature here, “Advanced programmers (particularly people porting unmanaged C++ code) often ask us for more C++-like ability to do things with references without having to get out the big hammer of actually using pointers and pinning memory all over the place. By using managed references you get these benefits without paying the cost of screwing up your garbage collection performance.” Also, a real world example this feature solves is given in this comment from a game engine developer. Now that you know about ref return go optimize your memory cache and game engines.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *