Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does declaring and instantiating a c# array actually mean?

I am reading up on c# arrays so my question is initially on arrays.

What does declaring an array actually mean? I know you declare a variable of type array. When I have the following, what is actually happening?

int[] values;

Is it in memory by the time it is declared? If not then where is it? Is the array actually created here?

Then I go and instantiate an the array and initialise it with some values like:

int[] values = new int[] { 1, 2, 3 };

Does this actually go and create the array now? I have read that arrays are created when they are declared, others say that arrays are created when they are instantiated. I am trying to get my terminology right.

The same goes for an integer variable. If I have:

int value;

and

int value = 1;

When is int created? When is it added to memory?

Sorry for the dumb questions. I understand the concept but would like to know the technicallity behind the scenes of arrays.

like image 925
Brendan Vogt Avatar asked Jul 11 '13 11:07

Brendan Vogt


1 Answers

What does declaring an array actually mean?

You didn't actually declare an array, you declared an array reference. Big deal in .NET, the difference between reference types and value types is important. Just having the array reference variable isn't enough, an extra step is required to create the array object. Which requires the new keyword. Which physically allocates the storage for the array object in the place where reference type objects are stored, the garbage collected heap.

The same goes for an integer variable

No, big difference. That's a value type. If it isn't a field of a class, not that clear from your question, then it is a local variable of a method. It gets created when the method starts running and poofs out of existence when the method returns. Very highly optimized, the core reason that value types exist in C#. The physical storage location is typically a cpu register or a slot on the stack frame if the method uses too many local variables.

If it is actually a member of a class then it gets created when the class object gets created. Just like an array, on the GC heap with the new keyword.

like image 63
Hans Passant Avatar answered Sep 20 '22 02:09

Hans Passant