C# 7 – reference returns & local references


In on of the last posts, we talked about some of the big features that came with C# 7. In this post, we will continue on that and we will talk about returning references from functions and storing references inside of local variables.

In addition to existing feature where you can pass in the parameter by value or reference with C# 7, you can also return by reference. Also, you can store references to other variables inside of local (function) variables.

It is important to note that local ref variables and returns can’t be used with async methods.

Reference inside of functions

We can now store a reference to another variable inside of the same function:

This will print out Points: 125.

We can also store a reference to a field of class inside of a function:

We can also have a reference to an element of the array:

However, we can NOT have a local reference (ref variable) to a property or a reference to some function that returns a value. It must be either assignable local variable, a field or an element of the array.


Reference returns

Being able to return a reference from a function means that a local reference variable inside of another function can consume and change the value for given reference.

The result will print out grade with a value of 17.

If we want to consume the reference that a function return we must declare a local variable as ref:

ref int grade

In case we use var keyword the compiler will not specify the ref int type, only int. That means that we can either have a regular int or a ref int variable when we want to consume a result of a function that returns ref.



Even though these two additions to the language might not seem that useful, they can be. One example would be handling data structures with different algorithms that enable us using references instead of copying values and wasting memory. 

We can also split out such code into functions or local functions and happily have references to anything we need, without being worried about performance downsides.

Ibrahim Šuta

Software Engineer, Mentor and Consultant interested and specialising in ASP.NET Core, C#, JavaScript, Angular, React.js. Experienced in MeteorJS, Node.js, ASP.NET, Windows Forms and Web Forms as well.