Passing and returning arrays.

1. How arrays are passed to a method?

2. What we should be aware of?

3. What is the Microsoft recommendation about returning arrays or fields?

Arrays are always passed by reference to a method, so to avoid changing of its elements we can create a copy of array by using Array.Copy methods. Remember that Array.Copy methods always makes a shallow copy so its elements can be referenced to original elements.

Similarly, if your method returns a reference to an array be aware that you really want to give an access to the internal array or make a copy and return copy of this array.

Microsoft recommends that we initialize returning arrays or field even with zero elements in it.

For example this code slightly more dificult to read:

            object[] array = GetNotInitializedArray();

            if (array != null)

            {

                foreach (object obj in array)

                {

                    Console.WriteLine();

                }

            }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s