Simplified Array Initialization Expressions - CSharp Language Basics

CSharp examples for Language Basics:Array

Introduction

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'};

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 = "sausage";   // s is implicitly of type string

// 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}
};

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

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

Related Tutorials