Array Reference Types Example

This is another program that demonstrates how arrays are reference types.

ArrayRefTypesSolution

 

Program.cs code contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArrayRefTypes
{
    class Program
    {
        /// <summary>
        /// Demonstrating how collections are reference types.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            int[] x1 = { 1, 4, 9, 16 };
            var x2 = x1;

            // Showing that if you change a array element it's referenced in the x2 variable.
            Console.WriteLine("x1[0] Before: {0}", x1[0]);
            x1[0] = -3;
            Console.WriteLine("x1[0] After: {0}", x1[0]);
            Console.WriteLine("RefEquals(x1, x2): {0}", ReferenceEquals(x1, x2));

            // Seeing what happens if I create another array and see of it points to the x1 reference.
            int[] x3 = { 1, 4, 9, 16 };
            Console.WriteLine("RefEquals(x1, x3): {0}", ReferenceEquals(x1, x3));

            Console.ReadLine();
        }
    }
}

What I’m doing here is showing how an array is a true reference type. And by changing the value of an array element it is changing the value of the reference.

How I’m doing this is by declaring an array type, assigning element values, declaring another variable with the value of the array, and changing an element value in the first array. To show that the value of the array and the value of the variable are the same I’m using the ReferenceEquals .NET method for this comparison and it shows as true. Meaning that the references are pointing to the same memory address.

Also to further cement the fact I’m declaring another array with element values and using the ReferenceEquals method to compare it to the first array showing that it’s false. Meaning that the reference values do not point to same memory address.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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