Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is this syntax for initializing collections called?

I have a basic C# program to demonstrate this:

namespace ConsoleApp5
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<int> list = [1, 2, 3, 4, 5, 6];
            List<int> list2 = [.. list];
        }
    }
}

What is the name for the trick being used to initialize list2?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

They’re known as collection expressions, introduced in C# 12 / .NET 8:

A collection expression is a terse syntax that, when evaluated, can be assigned to many different collection types. A collection expression contains a sequence of elements between [ and ] brackets

The [.. list] syntax is known as a spread element, it’s the same as inlining the entire list:

You use a spread element .. to inline collection values in a collection expression.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading