Inline arrays in C# offer a streamlined way to define arrays directly within expressions. This feature, introduced in C# 12, simplifies array initialization, making your code cleaner and more readable.
using System;
class Program
{
static void Main()
{
int[] numbers = [1, 2, 3, 4, 5];
string[] words = ["hello", "world"];
object[] mixed = [1, "two", 3.0];
Console.WriteLine(string.Join(", ", numbers)); // Output: 1, 2, 3, 4, 5
Console.WriteLine(string.Join(", ", words)); // Output: hello, world
Console.WriteLine(string.Join(", ", mixed)); // Output: 1, two, 3
}
}
Numbers Array: int[] numbers = [1, 2, 3, 4, 5]; creates an array of integers.
Words Array: var words = ["hello", "world"]; creates an array of strings.
Mixed Array: var mixed = [1, "two", 3.0]; you can even mix types in an object array.
Advantages of using inline arrays in C#:
Simplicity: Reduces the verbosity of array initialisation.
Readability: Makes the code easier to understand at a glance.
Inline arrays make initialising arrays effortless and visually cleaner.
tags:
C#12 Inline Arrays