Ref local re-assignment – C# 7.3 in Rider and ReSharper

The Early Access Preview (EAP) versions of ReSharper 2018.2 and Rider 2018.2 come with support for C# 7.3. In this series, we are looking at these new language features in C# 7.3. Today, we let’s check out ref local re-assignment.

This post is part of a series (we will update the table of contents as we progress):

Ref local re-assignment

In C#, it’s been possible for a while to work with references, using the ref keyword. For example, it’s possible to return a reference to a Person that is already in memory, rather than return a by-value version that will be copied.

If we’d call our method and assign the variable locally, this would essentially read the value of what was returned, and then assign it to a new variable:

var person = people.GetPerson(123);

Whenever we now make a change to the person, that change is made to the local copy of person, not to the one that was originally returned by GetPerson(). Even though that method returned a Person by reference.

C# 7.2 and C# 7.3 added a number of additions to working with references and the ref keyword. In C# 7.2, the ability to replace a referenced variable was added. Consider the following example:

We have effectively re-assigned people[0] in this case, which may (or may not) be intentional. Use with caution!

Perhaps this was unintentional after all, and all we wanted to do was to re-use the personRef variable to hold a reference to another object. For those cases, C# 7.3 adds ref local re-assignment (spec), to make it possible to re-assign an existing reference:

Do keep in mind that, for example, changing personRef.Name will update the original person in our array as well.

Download ReSharper 2018.2 EAP now! Or give Rider 2018.2 EAP a try. We’d love to hear your feedback!

This entry was posted in How-To's and tagged , , , , , . Bookmark the permalink.

3 Responses to Ref local re-assignment – C# 7.3 in Rider and ReSharper

  1. Pingback: Dew Drop - July 25, 2018 (#2773) - Morning Dew

  2. Mani says:

    Great article. You should make it explicit that Person is a struct not a class. It is confusing for people like me who always think of class…

Leave a Reply

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