Zshelley
Zshelley

Reputation: 45

Store the location of an array in C#

I want to be able to store a reference to an array, but not really sure if pointers are necessary or where to start. I'm looking for functionality similar to using ref with a function, but in a variable.

Upvotes: 2

Views: 766

Answers (2)

Alberto Solano
Alberto Solano

Reputation: 8227

A pointer (a reference to a memory location), in a high level language such as C#, is not necessary, if you want to store the reference to an array, because they're reference types. All reference type variables work like pointers, but the process of referencing to a memory location, in high level languages such as C#, is totally automatic and it is hidden to the user.

I have answered a question about pointers (in Java) here. Even if the language is different, Java is a high level language like C# and the process of referencing to a memory location is similar.

About your question, if you have an array like this:

int[] myArray = new int[2];

you can store its reference in another array like this:

int[] myStoredArrayRef = myArray;

Now, the two objects are referring to the same array, because they're referring to the same 'location' in memory (you copied its reference). Indeed, if you modify an element of myArray in this way:

myArray[0] = 123;

also the element of myStoredArrayRef will change:

Console.WriteLine(myStoredArrayRef[0]); //it will print '123';

You're able also to store a reference to a List, because they're reference types (as rightly pointed out by @DavidHeffernan) like the arrays, with the same procedure.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612993

Suppose you have an array:

int[] a = new int[42];

The variable a is a reference to the array. You can make another one like this:

int[] b = a;

Now a and b refer to the same array.

You can assign a value to an element like this:

a[0] = 666;

And then see that same value using the other reference:

Debug.Assert(b[0] == 666);

What this boils down to is the fact that arrays are reference types. So the assignment operator copies the reference to the object, and does not copy the object itself. Contrast this with value types, e.g. structs, for which the assignment operator copies the value of the object.

Upvotes: 4

Related Questions