C# Array Initialization

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'}; 
/*from   w w  w.  jav a2s  . co 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 
//w w w.ja  va 2s . c o m
// 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




















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var