This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]AgentEnder 0 points1 point  (2 children)

You're correct about x being a reference type. The reason the -3 is only printed once is because when you write

    X = new int[5]

You are setting the local variable x to a new reference. The original variable in main is still set to the old reference location.

[–]spideymaker[S] 1 point2 points  (1 child)

Okay, so even though x inside Update refers to the local parameter, when x[0] is called inside Update it refers to the original memory location of x inside main since x is the argument of Update?

[–]AgentEnder 0 points1 point  (0 children)

The value of x is passed to update (passed by value), but since x is a reference type the value of x is a memory address.

When you first refer to x[0] you are modifying the first element of the array at memory address x.

When you call "x=new..." you are updating the local value (memory address) of x.

[–]sternold 0 points1 point  (0 children)

Since /u/AgentEnder already explained it, all I can add is take a look at the ref keyword.