Search code examples
referenceref

pass ref parameter by value and set it to null


Consider the following code Snippet

Form form2 = new Form();

  test(form2);
  form2.Show();

public void test(Form f)
{
  f = null;
}

Since f also holds "another" reference to Form2, setting f to null should set Form2 to null as well, which it doesn't. Need a good explanation to understand this.


Solution

  • The reference set to null is the local copy of the form2 reference. As the reference is passed by value, meaning making an exact copy and passing the copy, the original remains untouched.

    The value passed here can be seen as a memory address (which is not exactly the case vith VMs but it is a helpful and adequate metaphor).

    In the test method, you set a variable holding a copy of this address to null. This has no further consequences whatsoever.

    The case is very different if you use the address stored in the variable to access and change the actual Object the address refers to. You are changing the real thing here, so all changes remain after your local variable runs out of scope.

    To take one more step back :

    You can see the variable as a slip of paper with an address of a friend (your object). If you burn the paper (setting the variable to null), your friend is not affected. If you use the paper to visit the address and give your friend a present or slap him in the face (calling a method on the object behind the variable), he is definitely affected and you have to live with the consequences