C# 12 - Collection Expression

Introduction

C# 12 includes new features like primary constructors, Inline arrays, Collection expression, ref readonly parameters, Alias any type, Default lambda parameters, Experimental attribute, and Interceptor. In this blog, we are going to see collection expressions.

Collection Expression in C# 12

A collection expression in C# provides a concise syntax for creating common collection values, and it can be assigned to various collection types. This syntax involves enclosing a sequence of elements within square brackets [ ]. For instance, consider the following example that declares an int[] containing integer elements.

int[] a =new int[] {1,2,3}; 

The above statement can be rewritten as a collection expression with C# 12.

int[] a = [1,2,3]; 

You can initialize the span as given below with C#12.

Span<int> t = ['a','b'];  

Summary

We have seen what and how to use collection expressions in C# 12. I will see more about Inline arrays in my next blog.