Does declaring an array create an array in C#?

CsharpProgrammingServer Side Programming

Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.

The following is a declaration and it will not create an array −

int[] id;

The following create an array of integers. The array is a reference type, so you need to use the new keyword to create an instance of the array −

Int[] id = new int[5] {};

Let us see an example −

Example

 Live Demo

using System;

namespace ArrayApplication {
   public class MyArray {
      public static void Main(string[] args) {
         int [] n = new int[5];
         int i,j;
     
         /* initialize elements of array n */
         for ( i = 0; i < 5; i++ ) {
            n[ i ] = i + 10;
         }

         /* output each array element's value */
         for (j = 0; j < 5; j++ ) {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
      }
   }
}

Output

Element[0] = 10
Element[1] = 11
Element[2] = 12
Element[3] = 13
Element[4] = 14
raja
Published on 31-Aug-2018 11:01:43
Advertisements