Liming
Liming

Reputation: 53

Call by reference not working as expected

In the example of Microsoft's web there are below codes:

class TestRef
{
    static void FillArray(ref int[] arr)
    {
        // Create the array on demand: 
        if (arr == null)
        {
            arr = new int[10];
        }
        // Fill the array:
        arr[0] = 1111;
        arr[4] = 5555;
    }
}

If I delete the line of if (arr == null), the error output will be 0 0 0 0 0 not 1 2 3 4 5. Why?

Upvotes: 1

Views: 90

Answers (3)

Nitin S
Nitin S

Reputation: 7591

Here in FillArray function you are passing the array by reference
but when you remove the if block
you re-initialize the array

when you initialize a value type array the elements take default value of the value type
In this case it is int which have default value 0

You need to understand pass by value vs pass by reference in C#
http://www.programminginterviews.info/2011/05/pass-by-value-versus-reference-in-c.html

also value type vs ref type
http://www.albahari.com/valuevsreftypes.aspx

Upvotes: 0

Neel
Neel

Reputation: 11721

its happening because when you put your code as it is it mean you are passing your intArray to the method but when you remove the lines as you have mentioned in this case new int[] is assigned to variable which will fill default 0 in your array.

this line arr = new int[10]; is assigning new int[] when you remove conditions.

As documented in the official site :-

A ref parameter of an array type may be altered as a result of the call. For example, the array can be assigned the null value or can be initialized to a different array.

Upvotes: 0

David Pilkington
David Pilkington

Reputation: 13620

This is because you are passing by ref this means that you are changing the pointer for that variable in the main method.

You are assigning it to a new int[] that is filled with the default value of int which is 0

Upvotes: 4

Related Questions