1

I'm bit confused on this.

private void button1_Click(object sender, EventArgs e)
{
    int i = 1;
    int[] p=new int[4];
    p[0] = 25;
    method(p);
    string o = p[0].ToString();
}
private void method(int[] k)
{
    k[0] = 34;
    k = null; //##
}

Scene 1 : If i remove k=null, then my p[0] turns out as 34 which was modified in 'method' function. Array is reference type so nothing to wonder.

Scene 2 : with k=null, still my p[0] returns 34 instead of null. Why it is so? here i'm making entire array as null but how still first element carries 34?

Ian
  • 30,182
  • 19
  • 69
  • 107
thoniv
  • 79
  • 1
  • 1
  • 11
  • 2
    You are *not* passing by reference. That requires the `ref` keyword. If you use the assignment operator (=), it will not affect the variable in the calling scope unless you pass by reference. However, if you change *properties* and *state* of a regular parameter, that *does* change the variable in the calling scope. – Millie Smith Mar 03 '16 at 04:44

2 Answers2

1

You are making the reference to the array null, you are not making the array null. If you change your argument to be ref int[] k and call it as method(ref p), then it would behave as you are expecting.

For example:

private void button1_Click(object sender, EventArgs e)
{
    int i = 1;
    int[] p=new int[4];
    p[0] = 25;
    method(ref p);
    string o = p[0].ToString();
}
private void method(ref int[] k)
{
    k[0] = 34;
    k = null; //##
}
Rob
  • 26,989
  • 16
  • 82
  • 98
1

Because what you do is passing the reference of the array to the method and it creates a new reference int[] k that refers to the same item as your caller's variable p does, but it is not p.

what becomes null is the new int[] k in the method, not the variable p from the caller.

int i = 1;
int[] p=new int[4]; //p is here
p[0] = 25;
method(p);
string o = p[0].ToString();

//this is k, it is a new int[] reffering to the same item as p, but not p
private void method(int[] k) 
{
    k[0] = 34;
    k = null; //##
}
Ian
  • 30,182
  • 19
  • 69
  • 107