Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0049 var array type

You can create an implicitly-typed array. We can use var to declare array and let C# figure out the array type. The type of the array instance is inferred from the elements in the array initializer. With implicitly-typed arrays, no square brackets are used on the left side of the initialization statement. using System; class Program { static void Main(string[] args) { var anArray = new int[] { 1, 2, 3 }; var rectMatrix = new int[,] // rectMatrix is implicitly of type int[,] { {0,1,2}, {3,4,5}, {6,7,8} }; var jagged = new int[][] // jagged is implicitly of type int[][] { new int[] {0,1,2}, new int[] {3,4,5}, new int[] {6,7,8} }; } } For single dimensional array C# can infer the type by converting all array elements to one type. using System; class Program { static void Main(string[] args) { var anArray = new[] { 1, 2, 3 }; } }