With new return ref
I feel like I'm going back to
my youth and good old C++. But for the start let's talk about
smaller change first (out
shortcut).
Out
out
improvement is small but useful. Now you
can push out
variable declaration inside function
call so you don't have extra line above just for variable
declaration (value1
and value3
below
are declared inside function call). You can also use var
since parameter type now can be inferred:
Two things to note from example above. You can use wildcard _
to skip some variables and variables
scope is not limited to the if
block only.
Return ref
Imagine you are writing monitoring system for a factory. Machine has sensors:
You would like to have code outside machine to manipulate those sensors. Classic solution is to
abstract machine into a simple interface and pass it to a sensor manipulation code. With new return ref
you can make code even simpler. You can return sensor itself and allow it to be manipulated from outside
code (SecondSensor()
is returning ref double
):
As per example above you can use ref
and "point" to a sensor (like good old C++ or unsafe C#).
Any change on a referenced variable will change machine sensor itself. The only downside is that you have to repeat
ref
keyword a lot! What I like is that you can omit ref
and get sensor value only.
Now the fun part. You can have function on the left side of equation with simple value type (if function is returning reference to a variable):
Code above is just an example what is possible and for sure not recommended style.
You can refer to a local variables:
Good news is that compiler will prevent you from doing "impossible" references.
You can't return local variable since it will disappear from the stack as soon as method returns:
Since array
goes on a heap you can return local array
:
Don't worry, compiler will prevent you from returning immutable:
Conclusion
C# is lifting some of its limitations but still it is a safe language. Returning reference is not that important to all users,
but if you are pushing performance to the maximum you will appreciate it for sure. Also, out
declaration shortcut
is a very useful change.