Mike Flynn
Mike Flynn

Reputation: 24325

Do collection initializers relate to LINQ in anyway like object initializers?

I am reading about LINQ and seeing Collection Initialzers come up, but does it really directly relate to LINQ like Object Initializers do?

List<string> stringsNew = new List<string> { "string 1", "string 2" };

Upvotes: 1

Views: 232

Answers (2)

Anthony Pegram
Anthony Pegram

Reputation: 126892

Collection initializers can be said to be related to Linq in so far as you can thank Linq that the feature made it into C# 3. In case something ever happens to the linked question, the useful text is

The by-design goal motivated by typical usage scenarios for collection initializers was to make initialization of existing collection types possible in an expression syntax so that collection initializers could be embedded in query comprehensions or converted to expression trees.

Every other scenario was lower priority; the feature exists at all because it helps make LINQ work.

-Eric Lippert

They are useful in the context of Linq because they give you the ability to write stuff like the below example

var query = from foo in foos 
            select new Bar 
            {
                ValueList = new List<string> { foo.A, foo.B, foo.C }
            };

Where you can construct a query that projects a given foo into a Bar with a list of foo's property values. Without such initializer support, you couldn't create such a query (although you could turn ValueList into a static-length array and achieve something similar).

But, like object initializers and other features that are new with C# 3+, many features inspired or added expressly to make Linq work are no doubt useful in code that has nothing at all to do with Linq, and they do not require Linq to work (either via a using directive or DLL reference). Initializers are ultimately nothing more than syntactic sugar that the compiler will turn into the longer code you would have had to write yourself in earlier language versions.

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564451

Object and Collection Initializers have nothing to do with LINQ - they're a completely unrelated language feature.

Any class with an Add method that implements IEnumerable can use a collection initializer. The items in the braces will be added, one at a time, instead of having to repeatedly call inst.Add(item1).

Upvotes: 0

Related Questions