DEV Community

Nick
Nick

Posted on

What is Inline Arrays in C# 12

Inline arrays in C# 12 are a powerful new feature that allow us to declare and initialize arrays in a more concise and intuitive way. Before C# 12, when we wanted to create an array, we had to use the traditional syntax, specifying each element one by one. However, with the introduction of inline arrays, the process has become much simpler.

To use inline arrays, we can simply enclose the elements within curly braces. For example, if we want to create an array of integers containing the numbers 1, 2, and 3, we can do so using the following syntax:

int[] numbers = { 1, 2, 3 };

This eliminates the need for explicitly declaring the size of the array and specifying each element individually. We can create arrays of any type using this approach, whether it be integers, strings, objects, or even custom-defined types.

Inline arrays also support features such as range expressions and index expressions. This means that we can specify a range of elements to initialize or access within the inline array declaration itself. For instance, if we only want to initialize the first three elements of an array, we can do so using the following syntax:

int[] numbers = { 1, 2, 3, 4, 5, 6 }[..3];

This will create an array containing only the elements 1, 2, and 3. Likewise, we can also use index expressions to access specific elements from an existing inline array.

Overall, inline arrays in C# 12 provide a more concise and flexible way of working with arrays. They simplify the process of initializing and accessing array elements, making our code cleaner and easier to read.

Top comments (0)