C# is pretty interesting to write and it is so so fascinating too
There are different ways to initialize an array in C#, stick to the end, I will show you different ways to go about it. The best approach will depend on a lot of factors, most especially preference(in my opinion).
Now let's dive in.....
While there have been latest changes in the last upgrade to C# which is C# 12, I would go all the way back to how it started, well maybe not all the way back. The aim here is to show you all the possible syntaxes to initialize array in C#.
Below is the list of possible array declarations and initializations:
string[] array = new string[2];
string[] array = new string[] { "A", "B" };
string[] array = { "A" , "B" };
string[] array = new[] { "A", "B" };
string[] array = ["A", "B"];
let's explain each of them
string[] array = new string[2];
This syntax creates a new array of strings that has a length of 2. It is like making an box with space for just two words in it, but we haven't put any words in it yet.
string[] array = new string[] { "A", "B" };
This syntax creates a new array of strings with an explicit initialization. The array is already filled with two elements: "A" and "B". It's like making a box and immediately putting the two words inside it.
string[] array = { "A" , "B" };
This is a shorter way of creating a new array of strings, it just only omits new string[]
.but is does the same as the example above. it is like a quicker route to get to the same destination.
string[] array = new[] { "A", "B" };
This is similar to the second example but it uses the new[] syntax. This syntax allows the compiler to infer the type of the array elements based on the initializer values. Since the initializer values are strings, the array will be of type string[]
. This is like telling the computer to figure out what you are putting in the box
string[] array = ["A", "B"];
This is the newest way to initialize an array in C# 12, simple and straightforward. It's also similar to the way arrays are initialized in Python and JavaScript. This makes it easier for developers familiar with those languages to work with arrays in C#.
Starting from C# 3 and above, there is a shorter way to write the first two and fourth declarations. You can write them like this:
var array = new string[2];
var array = new string[] { "A", "B" };
var array = new[] { "A", "B" };
This is possible because the information on the right side of the assignment is enough to infer the proper type of the array. This makes the code simpler and more concise.
To wrap this up, it is worthy to note that there are other ways to declare or initialize an array in C#, but we will stick to this methods. These methods cover the most common and straightforward approaches to working with arrays in C#
Thank you for reading
You can check me on LinkedIN
Top comments (0)