85. Assigning an array to var

As a rule of thumb, assigning an array to var doesn't require brackets, []. Defining an array of int via the corresponding explicit type can be done as follows:

int[] numbers = new int[10];

// or, less preferred
int numbers[] = new int[10];

Now, trying to intuit how to use var instead of int may result in the following attempts:

var[] numberArray = new int[10];
var numberArray[] = new int[10];

Unfortunately, none of these two approaches will compile. The solution requires us to remove the brackets from the left-hand side:

// Prefer
var numberArray = new int[10]; // inferred as array of int, int[]
numberArray[0] = 3; // works
numberArray[0] = 3.2; // doesn't work
numbers[0] = "3"; // doesn't work

There is a common practice to initialize an array at declaration time, as follows:

// explicit type work as expected
int[] numbers = {1, 2, 3};

However, trying to use var will not work (will not compile):

// Does not compile
var numberArray = {1, 2, 3};
var numberArray[] = {1, 2, 3};
var[] numberArray = {1, 2, 3};

This code doesn't compile because the right-hand side doesn't have its own type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.236