concept single expression in category c#

appears as: single expression, single expressions
C# in Depth, Fourth Edition

This is an excerpt from Manning's book C# in Depth, Fourth Edition.

LINQ also brought other benefits for initialization in the form of object initializers and collection initializers. These allow you to specify a set of properties to set on a new object or items to add to a new collection within a single expression. It’s simpler to show than describe, and I’ll borrow an example from chapter 3. Consider code that you might previously have written like this:

Object initializers and collection initializers make it easy to create new objects or collections with initial values, just as you can create and populate an array in a single expression. This functionality is important for LINQ because of the way queries are translated, but it turns out to be extremely useful elsewhere, too. It does require types to be mutable, which can be annoying if you’re trying to write code in a functional style, but where you can apply it, it’s great. Let’s look at a simple example before diving into the details.

3.3.4. The benefits of single expressions for initialization

You may be wondering what all of this has to do with LINQ. I said that almost all the features in C# 3 built up to LINQ, so how do object and collection initializers fit into the picture? The answer is that other LINQ features require code to be expressible as a single expression. (For example, in a query expression, you can’t write a select clause that requires multiple statements to produce the output for a given input.)

The ability to initialize new objects in a single expression isn’t useful only for LINQ, however. It can also be important to simplify field initializers, method arguments, or even the operands in a conditional ?: operator. I find it particularly useful for static field initializers to build up useful lookup tables, for example. Of course, the larger the initialization expression becomes, the more you may want to consider separating it out.