C# – How to initialize an array

Array is a fixed size collection of variables representing the same type. Array can store both built-in primitive types (like integer) and custom objects. In this article we’ll present different ways of initializing such arrays.

Array of integers

Let’s consider an array of integers. Below are presented five different methods of creating 3 elements array, where first one is empty and other four are prepopulated with values.

Now, let’s print every element of second array to the console using for loop.

Array of custom objects

Having a knowledge how to initialize array of simple types, let’s do the same with custom objects. For such purpose let’s define class called Person, containing two properties: Forename and Surname.

The same as previously, let’s create five arrays, able to store 3 Person objects each. As you can see, we can use exactly the same syntax as for integers. And again, first array is empty, whilst other four are prepopulated.

This time let’s print values of fifth array to the console using foreach loop. If you want, you still could do that with for loop.