ref for variables not parameters in functions

Aperture picture Aperture · Feb 7, 2011 · Viewed 10.6k times · Source

Suppose I have a Person class and have the following:

Person A = new Person("Tom");
Person B = A;

Is there a way I can change it so that if I assign a new Person to B, B = new Person("Harry"), A would be referring to the same instance too? I know you can do that in a ref parameter assignment in a function.

Answer

Eric Lippert picture Eric Lippert · Feb 7, 2011

UPDATE: The feature described here was added to C# 7.


The feature you want is called "ref locals" and it is not supported in C#.

The CLR does support generating code that contains ref locals, and a few years ago I wrote an experimental version of C# that had the feature you want, just to see if it would work. You could do something like:

Person a = whatever;
ref Person b = ref a;

and then as you say, changes to "b" would change the contents of "a". The two variables become aliases for the same storage location.

Though it was a nice little feature and worked well, we decided to not take it for C#. It's possible that it could still happen in a hypothetical future version of the language, but I would not get all excited about it in expectation; it will probably not happen.

(Remember, all of Eric's musings about hypothetical future versions of any Microsoft product are For Entertainment Purposes Only.)