Object Initializer
Let's use object initializers with arrays 😁
We can declare, assign and initialize the array at once to avoid writing assignments as separate operations.
This is where the object initializer shines:
string[] fruits = new string[4] { "apple", "cherry", "pineapple", "plum" };
We can also leave out the size because the compiler is smart enough to infer/know that.
So, we can remove 4
:
string[] fruits = new string[] { "apple", "cherry", "pineapple", "plum" };
Other approaches
Well, this intelligence of the compiler can lead us to other places as well 🤓.
Because the compiler can infer many things, we can simplify the way we create arrays.
- we can leave out the type (in our case
string
):
string[] fruits = new[] { "apple", "cherry", "pineapple", "plum" };
- we can also leave out the
new[]
altogether:
string[] fruits = { "apple", "cherry", "pineapple", "plum" };
- or we can make use of the
var
keyword, but in this case, we need to specify thenew[]
part.
var fruits = new[] { "apple", "cherry", "pineapple", "plum" };
Implicitly Typed Arrays
The third approach is called an Implicitly Typed Array because its type is inferred based on the assignment.
They are great for object initializers and anonymous types.
new[]
?
Why do we still need The second approach works because on the left side of the declaration we defined the type (in that case string[]
).
But if we use var
, there is no way for the compiler to know what is the type of the initialization.
Choices
So, which one to use?
I recommend using the third option because it uses the var
keyword and it makes writing code faster.
In addition, if you want to emphasize that those are indeed strings, you can specify that with new string[]
:
var fruits = new string[] { "apple", "cherry", "pineapple", "plum" };
It's up to you how much clarity you want to convey in your code. 😊
Let's display the values with a foreach
loop:
foreach(var fruit in fruits)
{
Console.WriteLine(fruit);
}
Conclusion
This is how you initialize arrays in C#. 🌟