C# Array Initialization

In this chapter you will learn:

  1. What is C# Array Initialization
  2. How to do C# Array Initialization
  3. Default Element Initialization
  4. Simplified Array Initialization Expressions

Description

An array initialization expression specifies each element of an array.

Syntax

For example:

char[] vowels = new char[] {'a','e','i','o','u'};

or simply:

char[] vowels = {'a','e','i','o','u'};

Default Element Initialization

Creating an array always preinitializes the elements with default values.

The default value for a type is the result of a bitwise zeroing of memory.

For example, int is a value type, this allocates 1,000 integers.

The default value for each element will be 0:


int[] a = new int[1000]; 
Console.Write (a[123]);            // 0 

Simplified Array Initialization Expressions

There are two ways to shorten array initialization expressions. The first is to omit the new operator and type qualifications:


char[] vowels = {'a','e','i','o','u'}; 
//w w  w  .  j  a  v a 2s.c  o  m
int[,] rectangularMatrix = 
{ 
  {0,1,2}, 
  {3,4,5}, 
  {6,7,8} 
}; 

int[][] jaggedMatrix = 
{ 
  new int[] {0,1,2}, 
  new int[] {3,4,5}, 
  new int[] {6,7,8} 
}; 

The second approach is to use the var keyword, which tells the compiler to implicitly type a local variable:


var i = 3;           // i is implicitly of type int 
var s = "java2s.com";   // s is implicitly of type string 
//from  ww w  .  ja v  a 2  s .  c om
// Therefore: 

var rectMatrix = new int[,]    // rectMatrix is implicitly of type int[,]                          
{                                                                                                  
  {0,1,2},                                                                                         
  {3,4,5},                                                                                         
  {6,7,8} 
}; 

var jaggedMat = new int[][]    // jaggedMat is implicitly of type int[][] 
{ 
  new int[] {0,1,2}, 
  new int[] {3,4,5}, 
  new int[] {6,7,8} 
}; 

You can omit the type qualifier after the new keyword and have the compiler infer the array type with single-dimensional arrays:

var vowels = new[] {'a','e','i','o','u'}; // Compiler infers char[]

The elements must all be implicitly convertible to a single type in order for implicit array typing to work. For example:

var x = new[] {1,10000000000}; // all convertible to long

Next chapter...

What you will learn in the next chapter:

  1. Initializing a Jagged Array
  2. Length with jagged arrays
  3. Use foreach statement to loop through jagged array
Home »
  C# Tutorial »
    C# Language »
      C# Array
C# Arrays
C# Array Length
C# Array Rank
C# Array Index
C# Multidimensional Arrays
C# Array Initialization
C# Jagged Array
C# Array foreach loop
C# Array ForEach Action