Ref returns and locals in C# 7.0

We need to pass data to the functions very frequently. We can either pass data to the function by values or by reference. In C# ref modifier is used to pass data by reference. Passing by reference means that we are grabbing the address of the data and sending that address to the calling method. Now if the value changes into passed data in the calling method, the data will be changed for that reference in the caller method as well. The code below is doing very simple job. It is just passing a value by reference and then adding 2 to the value. And the result is that the value of x is also getting updated in the caller method. But I have put a bit of twist in here. As you can see I am actually returning the value from the method and it is also being stored in another variable y. By showing the values of both the variables in Console you will get to know that at first they both are same. But when I change the value of y to 5 and showing it again in Console, the value of x is not getting effected. The reason for this is that y is a value type and has its own different memory location. So changing anything in that will not effect the value of x. Now let us improve this program with the features of C# 7.0.

refex1

To make y to act as a reference type we will have to mark it with ref modifier and also in the method call we will have to prefix ref keyword to mention the type being returned is a reference type. In prior versions to C# 7.0 it was just possible to set ref modifier with the arguments being passed. But now in this latest coming version it is possible to use ref modifier as return type. You can also create a ref data type of any particular data type. Also the ref modifier will be placed before the calling method to return the reference.

refex2

Now following is the complete updated code. In this code value of x will change when the value of y changes as the y is a reference to an integer and referencing the address of x.

refex3

  • Show Comments (0)

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

comment *

  • name *

  • email *

  • website *