Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name for the "AddRange" collection initializer? [duplicate]

Tags:

c#

collections

There's a C# feature which I don't know the term for, and as such haven't been able to find documentation on it.

What is the name for the "AddRange-like" syntax that lets you add elements to a collection during initialization? I'm referring specifically to the case documented in the code below, where we are not calling the constructor (and are unable to due to the property not having a setter), but instead seem to just be calling AddRange on the collection.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main(string[] args)
    {
        TestClass a = new TestClass()
        {
            // What is the name for this feature??
            List =
            {
                0,
                10,
                20,
                30
            }
        };
        Console.WriteLine(a.List.Count);
    }

    public class TestClass
    {
        private List<int> _list = new List<int>();
        public List<int> List { get { return _list; } }
    }
}

Also, am I understanding the semantics of this syntax correctly? It is just allowing us a to shorthand AddRange/multiple-Add syntax on a collection, correct?

.NET Fiddle here, should anyone want to run the sample code: https://dotnetfiddle.net/i01HYv

like image 912
bsinky Avatar asked Nov 19 '25 09:11

bsinky


1 Answers

Its the Object Initializer or Collection Initializer syntax introduced in C# 3.0

like image 163
PhillipH Avatar answered Nov 20 '25 22:11

PhillipH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!