Raghu
Raghu

Reputation: 3079

Why does not ref int value change from the original value in C# 7.3?

I have following code:

    static void Main(string[] args)
    {
        var x = 9;
        var y = 23;
        Console.WriteLine($"x = {x}, y = {y}");

        var z = SomeMethod(ref x, y);

        Console.WriteLine($"x = {x}, y = {y}, z = {z}");

        z = 20;
        Console.WriteLine($"x = {x}, y = {y}, z = {z}");

        Console.ReadLine();
    }

    private static ref int SomeMethod(ref int x, int y)
    {
        x++;
        y++;
        return ref x;
    }

Please note the ref on the method return signature of SomeMethod.

This produces following output:

x = 9, y = 23
x = 10, y = 23, z = 10
x = 10, y = 23, z = 20

I was expecting the value of x on the last line to be same as z value. What am I missing?

Upvotes: 3

Views: 121

Answers (2)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

According to the documentation, when you do this:

int z = SomeMethod(ref x, y);

You are only keeping the value returned by SomeMethod (giving that structs, such as int, are value types).

What you are looking for is the ref local feature, which is achieved by the following:

ref int z = ref SomeMethod(ref x, y);

Then, when you modify z, you are actually modifying x:

x = 9, y = 23
x = 10, y = 23, z = 10
x = 20, y = 23, z = 20

Upvotes: 3

Patrick Hofman
Patrick Hofman

Reputation: 156988

You are missing that we are not talking objects or pointers.

You simple set the value of z to 20. That has nothing to do with the refs you copied around.

Upvotes: 4

Related Questions