Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a reference inside a C# function like C++?

Tags:

c#

reference

In C++ I can do this:

 int flag=0,int1=0,int2=1;
 int &iRef = (flag==0?int1:int2);
 iRef +=1;

with the effect that int1 gets incremented.

I have to modify some older c# code and it would be really helpful if I could do something similar, but I'm thinking ... maybe not. Anybody?

like image 406
Gio Avatar asked Jul 19 '10 20:07

Gio


1 Answers

UPDATE: The feature discussed below was finally added in C# 7.


The feature you want - to make managed local variable aliases is not supported in C#. You can do it with formal parameters - you can make a formal parameter that is an alias of any variable - but you cannot make a local which is an alias of any variable.

However, there is no technical difficulty stopping us from doing so; the CLR type system supports "ref local variables". (It also supports ref return types but does not support ref fields.)

A few years back I actually wrote a prototype version of C# which supported ref locals and ref return types, and it worked very nicely, so we have empirical evidence that we can do so successfully. However, it is highly unlikely that this feature will be added to C# any time soon, if ever. See http://ericlippert.com/2011/06/23/ref-returns-and-ref-locals/ for details.

I note that if I were you, I would avoid this in any language. Writing programs in which two variables share the same storage makes for code that is hard to read, hard to understand, hard to modify and hard to maintain.

See also the related question: Why doesn't C# support the return of references?

like image 186
Eric Lippert Avatar answered Sep 22 '22 10:09

Eric Lippert