What array initialization syntaxes do you know?

Experience Level: Mid-level
Tags: .NET C#

Answer

Explanation

int[] array = { 1, 2, 3 }; // Creates array with 3 items

int[] array = new int[] { 1, 2 }; // Creates array wihh 2 items

int[] array = new int[10]; // Creates array with 10 items that have default value 0

var array = new [] { 1, 2, 3 }; // Creates int array with 3 items

For the second and third example the explicit type declaration could be replaced by using var keyword. For the first case the var keyword cannot be used as the information on the right hand side is not enough to infer the type.

Related C# job interview questions