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.
|
int[] array1 = new int[3];
int[] array2 = new int[3] { 1, 2, 3 };
int[] array3 = new int[] { 1, 2, 3 };
int[] array4 = { 1, 2, 3 };
int[] array5 = new[] { 1, 2, 3 };
|
Now, let’s print every element of second array to the console using for loop.
|
for (int i=0; i<3; i++)
{
Console.WriteLine(array2[i]);
}
|
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.
|
public class Person
{
public string Forename { get; set; }
public string Surname { get; set; }
}
|
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
Person[] array1 = new Person[3];
Person[] array2 = new Person[3]
{
new Person() { Forename = “John”, Surname = “Smith” },
new Person() { Forename = “Mary”, Surname = “Davies” },
new Person() { Forename = “James”, Surname = “Jones” }
};
Person[] array3 = new Person[]
{
new Person() { Forename = “John”, Surname = “Smith” },
new Person() { Forename = “Mary”, Surname = “Davies” },
new Person() { Forename = “James”, Surname = “Jones” }
};
Person[] array4 = {
new Person() { Forename = “John”, Surname = “Smith” },
new Person() { Forename = “Mary”, Surname = “Davies” },
new Person() { Forename = “James”, Surname = “Jones” }
};
Person[] array5 = new[]
{
new Person() { Forename = “John”, Surname = “Smith” },
new Person() { Forename = “Mary”, Surname = “Davies” },
new Person() { Forename = “James”, Surname = “Jones” }
};
|
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.
|
foreach (var person in array5)
{
Console.WriteLine(person.Forename + ” “ + person.Surname);
}
|
|
John Smith
Mary Davies
James Jones
|
Need Help with Your C# Projects?
We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.
CONTACT US NOW