#120 – Array Declaration and Instantiation

Three are three steps in declaring and using arrays in C#–declaration, instantiation and (optionally) initialization.

You start by declaring the array.

 int[] numbers;

At this point, the array has been declared but not instantiated.  We’ve declared a variable that references an array of integers, but no array has been created yet and the value of the variable is still null.

The next step is to instantiate the array.  We create the array of integers, assign memory for it, and set the variable to reference the newly created array.

 numbers = new int[4];    //  Instantiate

At this point, the array exists, but its elements all have default values.  For integer values, this default is 0.

We could declare and instantiate the array at the same time:

 int[] numbers = new int[4];    //  Declare / Instantiate

 

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #120 – Array Declaration and Instantiation

  1. Pingback: #121 – Array Initialization « 2,000 Things You Should Know About C#

  2. Pingback: #1,012 – Options for Array Declaration, Instantiation and Initialization | 2,000 Things You Should Know About C#

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

%d bloggers like this: