Chapter 2: Declarations and syntactic sugar
C# has many features that make code more concise, but shorter code is not always easier to read. Some features simply remove repetition; others affect type inference or even change program behavior.
This chapter reviews syntax used in later chapters, then focuses on newer features such as collection expressions, the field keyword, raw string literals, and labeled jump statements. We’ll compare alternative approaches and consider when each is appropriate.
2.1 Implicitly typed locals with var
When declaring a local variable with var, you can avoid repeating a type name. For example, these two alternative declarations create dictionaries of the same type:
In the first declaration, the compiler infers the variable’s type from the expression on the right. The second uses target-typed new, introduced in C# 9, to determine what object to create from the type on the left. Both are clear; what matters is whether the reader can tell what the variable represents.
var does not mean the variable can change its type later. Its type is determined at compile time, and subsequent type checking is the same as for an explicitly typed variable.
When to use var (and when not to)
When the type name already appears on the right or is excessively long, var often makes code easier to read. It is also useful with anonymous types (Section 2.6), whose names cannot be written directly in source code.
Conversely, if the method name and context do not make the return type clear, an explicit type may help:
This does not mean every method call needs an explicit type declaration. Consider whether the type information is important to understanding the code.
Pitfalls in type inference
When creating an array with new[], the compiler infers the array type from the elements. For example, new[] { 1, 2.5 } produces a double[], not an int[]. If you need to control the element type, specify it explicitly.
The C# 12 collection expression [1, 2, 3] differs from new[] { 1, 2, 3 }: the former needs a target type and cannot directly be used with var. See Section 2.3.
Source code: DemoVar
2.2 Dynamic typing with dynamic
C# 4.0 introduced the dynamic keyword to defer type checking to runtime.
var vs dynamic
Here’s a side-by-side comparison:
- The compile-time type is
string, and the runtime type is alsostring. - The compile-time type is
dynamic, while the runtime type isstring. - This fails at compile time: Cannot implicitly convert type
stringtoint. - This fails at runtime: Cannot implicitly convert type
stringtoint.
You can assign a dynamic variable to a var variable, but when you mix dynamic and var, there are a few details worth watching for:
dynamic and ExpandoObject
In practice, dynamic is often used together with System.Dynamic.ExpandoObject. The primary benefit of ExpandoObject is that it represents a dynamic object whose members (properties, methods, events) can be added, changed, or removed at runtime—without needing to define its shape at compile time. In short, it gives C# objects JavaScript-like flexibility.
The following example adds properties at runtime and passes the object to a method that accepts a dynamic parameter:
Notes:
dynamic obj = new ExpandoObject();: If you want to use dynamic member syntax such asobj.FirstName = ..., the variable’s compile-time type must bedynamic. If you change it tovar obj = new ExpandoObject();, the code still compiles, but the compile-time type becomesExpandoObject, so the later dynamic member access will no longer compile.obj.FirstName = "Bruce";andobj.LastName = "Wayne";: A dynamically typed object can have arbitrary properties added.
If you rewrite the ExpandoObject creation and property assignments using an anonymous type, it looks like this:
In this specific example, both approaches produce the same result because GetFullName takes a dynamic parameter and only needs FirstName and LastName to exist at runtime. That said, anonymous types and ExpandoObject are not equivalent: the members of an anonymous type are fixed once created, whereas ExpandoObject lets you add or remove members at runtime.
Source code: DemoDynamic
Costs of dynamic and alternatives
dynamic is useful in interoperability scenarios, but it comes at a cost: member-name errors may not be detected until execution reaches the affected line, IDE refactoring and symbol navigation cannot reliably follow dynamic members, and runtime binding adds call-site caching overhead. Dynamic code may also face restrictions in Native AOT or trimmed deployments.
A common misconception arises with JSON. With the default behavior of System.Text.Json, JsonSerializer.Deserialize<dynamic>(json) typically returns a boxed JsonElement, not an object whose JSON properties can be accessed directly through dynamic member syntax such as obj.Name.
Modern C# has consistently evolved to embrace the static type system rather than deferring type checks. Except for necessary interoperability scenarios (such as COM interop), you should prioritize strongly typed classes, records, or generics to guarantee compile-time type safety.
2.3 Collection expressions
C# 12 introduced collection expressions, which let us use square brackets [] to initialize multiple collection types. Besides shortening code, they make initialization of arrays, List<T>, and other types more consistent. The compiler can choose an appropriate implementation based on the target type.
Keep one key idea in mind: the [...] on the right only describes a sequence of elements; the actual result type is determined by the target type supplied by the left-hand side or the surrounding context.
For example, the same [1, 2, 3] can represent an int[], a List<int>, or a Span<int>, depending on the target type.
When to use them
This section highlights a few common situations where collection expressions are especially useful:
- Initializing collections
- Combining multiple collections
- Passing collection arguments to methods
- Creating empty collections
- Working with
Span<T>orReadOnlySpan<T>
Initializing collections
This is the most straightforward and one of the most common use cases. In the past, different collection types often required noticeably different initialization styles. Collection expressions make them look more consistent.
Before:
With collection expressions, you can use a single form:
As you can see, the code on the right now looks much more uniform. The compiler decides what to create based on the target type on the left. That is one of the biggest strengths of collection expressions: the syntax is more consistent, while the resulting type remains type-safe and semantically clear.
Combining multiple collections
If you need to combine several collections into a new one, collection expressions work especially well with the .. spread syntax. In many cases, this is more direct than AddRange, Concat(...).ToArray(), or manual copying.
Here, .. section1 means “take the elements in section1 and expand them into the new collection expression.”
Note
The
..here is spread syntax in a collection expression. It looks the same as the..used in list patterns in Chapter 6, but it serves a different purpose. Here it expands elements while building a new collection; in a list pattern, it matches a range of elements during pattern matching.
Passing collection arguments to methods
Collection expressions are not limited to variable declarations. They are also very convenient at call sites. As long as the parameter type is clear, you can often use [] directly.
The parameter type of PrintTags supplies the target type, so the compiler knows to create a string[]. The caller only needs to specify the elements.
Starting with C# 13/.NET 9, params parameters can use collection types other than arrays, such as IList<T>, Span<T>, and ReadOnlySpan<T>. Callers can pass individual elements or a collection compatible with the parameter type.
Creating empty collections
Empty collections are another place where collection expressions work well. Compared with older patterns like new string[0] or new List<int>(), [] is more direct and easier to read.
When the target type is clear, the compiler may also choose a more efficient implementation for an empty collection. For example, when the target type is T[], the compiler may use something similar to Array.Empty<T>()—a shared, pre-allocated empty array—rather than allocating a new one each time.
Working with Span<T> or ReadOnlySpan<T>
Besides arrays and List<T>, collection expressions support Span<T> and ReadOnlySpan<T>. These types provide views over contiguous memory without necessarily copying the data, and are often used in string parsing and performance-sensitive code. Here we focus on initialization syntax; Chapter 13 covers memory allocation and lifetime.
When the target type is Span<T> or ReadOnlySpan<T>, the compiler may use stack allocation when the data is small enough and does not escape the current stack frame, but this does not guarantee behavior identical to hand-written stackalloc. Chapter 13 returns to this topic from the perspective of high-performance memory handling.
Source code: DemoCollectionExpressions
Collection expression arguments (C# 15)
Suppose we need article tags that are case-insensitive. For example, "C#" and "c#" should be treated as the same tag. A HashSet<string> (a collection that does not allow duplicate elements) can accept a comparer when constructing the collection to determine whether elements are equal.
In C# 14 and earlier, we can write:
C# 12 collection expressions simplified element initialization, but did not allow us to supply the comparer inside the brackets. When constructor arguments were needed, we still had to use the preceding syntax.
C# 15 introduces collection expression arguments. Put with(...) first inside the brackets to pass arguments to the collection’s constructor:
Both alternatives produce two tags ("C#" and "dotnet"), and tags.Contains("c#") returns true in both. The new syntax lets us specify a comparer while retaining the consistent collection expression syntax; it does not change the comparison rules or add new collection functionality.
Another common need is to specify the initial capacity of a List<T>. If you plan to append more items later, you can reserve extra capacity:
This specifies the initial capacity, not the number of elements. Whether reserving additional capacity is worthwhile depends on how many elements you expect to add.
with(...) must appear first in the collection expression. Arrays, Span<T>, and ReadOnlySpan<T> do not support these arguments, even an empty with().
Note
If a custom collection specifies a builder method through
CollectionBuilderAttribute, thewith(...)arguments are passed to that method before its finalReadOnlySpan<T>element parameter. For custom collection design, see Microsoft’s Collection expressions.
Two common limitations
Collection expressions are powerful, but there are still two practical limitations: one involves type inference, and the other involves Dictionary.
You cannot rely on var to infer the type
The following does not compile:
var numbers = [1, 2, 3]; // ✘ Won't compileThe compiler rejects this because it does not know whether you want int[], List<int>, Span<int>, or some other supported collection type. You need to write the target type explicitly:
int[] numbers = [1, 2, 3]; // OK
List<int> values = [1, 2, 3]; // OKThis once again shows that collection expressions are target-typed syntax, not literals with a fixed natural type.
Limitations with dictionary initialization
Collection expressions are mainly designed for sequences of a single element type. For a type like Dictionary<TKey, TValue>, which has key-value semantics, there is no corresponding key-value entry syntax. So if you want to create a dictionary with initial contents, you still need to use traditional initialization syntax, for example:
However, if you only need to represent an empty dictionary, you can still write:
2.4 Object initializers
Object initializers let us set properties when creating an object. Assume Student has two settable properties, Name and Birthday.
Note
To keep the examples focused on syntax, some later class snippets in this chapter omit nullable reference type handling. If nullable analysis is enabled in your project, properties such as
string Namewould typically need a default value, arequiredmodifier, or constructor-based initialization to avoid compiler warnings.

With constructors
Property assignment in the initializer takes place after the constructor finishes, so it can overwrite values set by the constructor. Suppose the Student(string name) constructor sets Name:
Keep this order in mind when designing constructor validation. For values that must be supplied when creating an object or should not be reassigned after initialization, see required and init in Chapter 4.
Source code: DemoObjectInit
Collection initializers
Collection initializers add elements when creating a collection. For example:
For List<T>, this syntax calls Add after creating the object. Collection expressions from Section 2.3 are another option, but initializers remain useful for collections such as dictionaries.
Source code: DemoCollectionInit
Index initializers (C# 6+)
Collections with indexers (such as Dictionary) can use a more concise syntax:
// C# 5 style
var students = new Dictionary<int, Student>
{
{ 101, new Student { Name = "Bob" } },
{ 102, new Student { Name = "Carol" } }
};
// C# 6+ index initializer syntax
var students = new Dictionary<int, Student>
{
[101] = new Student { Name = "Bob" },
[102] = new Student { Name = "Carol" }
};Note: The two syntaxes are not entirely equivalent: the older collection initializer ({ key, value }) calls Add under the hood and throws ArgumentException on a duplicate key, whereas the index initializer ([key] = value) uses the indexer and silently overwrites any existing entry. Keep this difference in mind when choosing between them.
Source code: DemoIndexInit
Object initializers vs optional parameters
Some developers use optional constructor parameters to achieve a similar effect:
Although they look similar, you should generally prefer object initializers when you’re designing a library for third-party use.
Optional parameter defaults are compiled into the caller. For example, if a library changes an int retryCount = 3 parameter to use 5, an already compiled client still passes 3 until it is recompiled. The program remains executable, but its behavior does not automatically follow the new library default. This matters when maintaining version compatibility.
If the class sets its own property defaults and callers use object initializers only to override them when necessary, those defaults need not be baked into caller code. However, if the chosen constructor still has omitted optional parameters, the version compatibility issue remains.
2.5 Auto-implemented properties
With an auto-implemented property, the compiler generates a private backing field to store the data. For example:
The second property restricts access to its setter, so code outside the class can read Id but cannot assign to it directly. Chapter 4 explains how init and required can further restrict changes after initialization or require callers to provide an initial value.
Source code: DemoAutoPropBasic
The field keyword (C# 14)
C# 14 introduced the field keyword so that, inside an accessor, you can directly access the compiler-generated backing field—without manually declaring a private field. This is a significant improvement for auto-properties.
Before the field keyword, if you wanted validation in a setter, you typically had to declare a private field:
With the field keyword, you can keep the validation logic while avoiding the private field declaration:
This approach has a few clear advantages:
- Less boilerplate: No private field declaration, and no separate field name to maintain.
- Fewer mistakes: Validation and auto-properties can coexist without you having to remember the right field name.
- Safer refactoring: Renaming the property doesn’t require renaming a separate field.
One subtle point: once any accessor of a property uses the field keyword, the compiler synthesizes a backing field for that property. In practice, that means the other accessors of the same property should usually use field consistently as well (or remain auto-accessors), rather than mixing field with a manually declared field. The following example still compiles, but it produces warning CS9266. The reason is that the getter reads from the compiler-generated field, while the setter writes to the manually declared _count. The two accessors therefore operate on different storage locations, so writing through the setter does not update the field read by the getter. For example, after assigning 5 to Count, reading it still returns 0:
Here are a few common patterns. The final Email property only demonstrates calling a notification method when the value changes. OnPropertyChanged is an empty stub, not a complete MVVM notification implementation. Chapter 9 covers event design and subscriptions.
public class Person
{
// Read-only property: the compiler still generates a backing field,
// but this property does not use the `field` keyword explicitly
public string Id { get; } = Guid.NewGuid().ToString();
// Property with validation
public string Name
{
get;
set => field = value ??
throw new ArgumentNullException(nameof(value));
} = "";
// Property change notification (common in MVVM)
public string Email
{
get;
set
{
if (field != value)
{
field = value;
OnPropertyChanged();
}
}
} = "";
private void OnPropertyChanged(
[CallerMemberName] string? name = null) { }
}Source code: DemoAutoPropField
Note: If your type already has a member named field (a field, property, method, etc.), you can use @field or this.field to disambiguate.
2.6 Anonymous types
In LINQ queries, we often need only a few properties of the original data, without defining a new class for the temporary result. Anonymous types are useful in this situation.
The compiler generates a class based on the property names and types, with read-only properties. Because the class name cannot be written directly in source code, we normally declare the variable with var.
Source code: DemoAnonTypeBasic
Type reuse
Within the same assembly, the compiler uses the same anonymous type when property names, types, and order match. For example:
Value equality
Anonymous types also have a practical feature: the compiler implements Equals and GetHashCode for them. Therefore, two instances are considered equal when they are instances of the same anonymous type (that is, the compiler reused the type because the property names, types, and order all match) and all property values are equal:
This makes anonymous objects useful in LINQ operations like grouping (GroupBy) or deduplication (Distinct).
Projection initializers
When creating an anonymous type, you can omit a property name if it matches the original variable or property name. This is called a projection initializer.
Chapter 10 shows how to use this syntax to project LINQ query results.
Nondestructive mutation
Starting with C# 10, you can use the with expression on anonymous types. This is called nondestructive mutation: it creates a new object by copying all properties, while changing a selected subset. The with expression also works with records and structs—see Chapter 4 for details.
For example:
This is especially convenient when working with immutable data: you don’t have to retype every property just to change one.
Source code: DemoAnonTypeMutation
Limitations
Anonymous types are useful for intermediate LINQ results. When data needs to cross method or public API boundaries, a named type (such as a record) is usually a better choice, because callers can tell from the method signature what data is available.
An anonymous type itself does not implement IDisposable. If it contains resources that must be disposed of, the code must still dispose of those resources.
2.7 String interpolation
C# 6 introduced string interpolation, which lets you embed expressions directly in strings and often makes code read more naturally.
First, compare it with string.Format:
Source code: DemoStringInterpolation
Note: Starting with C# 10 (.NET 6), interpolation can be optimized via interpolated string handlers (see DefaultInterpolatedStringHandler). It’s no longer always lowered to string.Format or string.Concat. In many cases it allocates less and runs faster.
Formatting and alignment
An interpolation expression can use a colon to specify a format and a comma to specify the field width. For example:
A positive width aligns right; a negative width aligns left. Numeric output may also depend on the current culture.
Constant interpolated strings (C# 10)
Starting with C# 10, if every interpolation hole in an interpolated string is filled with a constant string, the interpolated string itself can be declared as const.
Example:
Raw string literals (C# 11)
Suppose we need JSON in our source code, perhaps as test data or an API example. Previously, a verbatim string literal (with @ before the opening quote) allowed multiple lines without escaping backslashes for C#. However, each double quote inside the JSON still had to be doubled.
C# 11 introduced raw string literals, which make strings containing many quotes and backslashes easier to read.
Raw string syntax
Wrap the content in at least three double quotes ("""):
Both examples produce the same string, but the raw string resembles the JSON we normally see and does not require doubling quotes for C# syntax.
Raw strings eliminate C# escaping, not the rules of JSON itself. For example, the C:\\Windows\\System32 above still uses two backslashes to represent one backslash in a JSON string.
For multiline raw strings, the closing """ determines the indentation. Here it has four leading spaces, so four spaces are removed from the start of each nonblank content line, while the JSON’s internal indentation is preserved. If the content needs three consecutive double quotes, use four as delimiters, and so on.
Combining with interpolation
You can combine $ with """. If your raw string contains many {} characters (common in JSON/CSS/JS), you can use multiple $ to change the interpolation delimiter.
For example, with $$, only {{…}} is treated as an interpolation hole; a single { is treated as plain text:
Rule summary:
$"text"→{expr}interpolates.$$"""text"""→{{expr}}interpolates; single{is plain text.$$$"""text"""→{{{expr}}}interpolates;{and{{are plain text.
This mechanism lets you generate structured text (JSON, XML, HTML, CSS, JavaScript) while keeping interpolation available. It is usually cleaner and less error-prone than manually escaping braces.
Interpolation does not automatically JSON-escape variable values. If name contains quotes, backslashes, or other special characters, direct interpolation may produce invalid JSON. Use a JSON serializer when converting arbitrary data to JSON; the fixed text here demonstrates the syntax. The example project also includes CSS interpolation.
Source code: DemoRawStringLiterals
2.8 Tuples and deconstruction
Before C# 7.0, if a method needed to return multiple values, you typically used out parameters, created a dedicated DTO type, or used System.Tuple (available since .NET 4.0). Each approach has drawbacks: out parameters are awkward (and cannot be used in async methods), creating dedicated types can be overly verbose, and the older System.Tuple forces meaningless member names like Item1 and Item2 upon you.
C# 7.0 introduced ValueTuple to address these pain points.
Tuple basics
If a class is like a sturdy but heavy suitcase, a tuple is more like a lightweight zippered bag: when you just need to carry a few related values together, a tuple is often the more straightforward choice.
You can use parentheses () to define a tuple and name its elements:
Under the hood, this syntax uses the generic struct System.ValueTuple<T1, T2, ...>. The compiler maps your custom element names to the underlying fields, so you’re no longer stuck with Item1 and Item2.
Returning multiple values
The most common use case is returning more than one value from a method:
For a case that simply returns two values together, a tuple is more direct than out parameters and can also be used in asynchronous methods. If the data is part of a long-lived public API contract or requires validation or methods, consider a named type such as a record.
Source code: DemoTupleBasic
Q: Why do some older codebases use Tuple.Create("Bob", 23)? How is it different from ("Bob", 23)?
A: The older System.Tuple is a class (a reference type), adding allocation pressure. The modern syntax uses System.ValueTuple, a struct (a value type), which typically does not require a separate object allocation for the tuple itself. Actual costs depend on usage, such as copying large value types or boxing. Prefer modern syntax for ordinary multiple-value returns; use System.Tuple where compatibility with older APIs requires it.
Deconstruction
C# also provides deconstruction syntax, which lets you “split” a tuple or other object into multiple independent variables:
You can also use var:
var (lat, lon) = GetCoordinates("Taipei 101");Discards
If you only need some of the returned values, you can use _ as a discard:
var (lat, _) = GetCoordinates("Taipei 101"); // We only need latitudeThis makes it clear to the reader that we’re intentionally ignoring certain values, not simply forgetting to use them.

Deconstructing custom types
Tuples aren’t the only deconstructable types. Any type can support deconstruction as long as it defines a special method named Deconstruct.
The following example lets Person support two deconstruction forms:
public class Person
{
public string Name { get; set; }
public DateTime Birthday { get; set; }
public string Email { get; set; }
// Define a Deconstruct method
public void Deconstruct(out string name, out DateTime birthday)
{
name = Name;
birthday = Birthday;
}
// You can overload Deconstruct
public void Deconstruct(out string name, out DateTime birthday,
out string email)
{
name = Name;
birthday = Birthday;
email = Email;
}
}Using it implicitly calls Deconstruct:
Source code: DemoTupleDeconstruction
Design guidelines:
Deconstructmust returnvoid.- Parameters must be
outparameters. - You can overload it by varying the number of parameters.
- It’s commonly used to expose key properties of a complex object.
2.9 Labeled jump statements (C# 15)
In nested loops, an ordinary break exits only the innermost loop, and continue advances only that loop to its next iteration. Controlling an outer loop traditionally requires extra code.
Pain points of nested loop breakouts
Suppose we are searching a two-dimensional grid for a target. Each cell has a Boolean property IsTarget. The grid has rows rows and cols columns. We scan from row 0, column 0, stopping at the first target and recording its coordinates.
We use the tuple from the previous section to store the row and column. The ? means the coordinates can be null (no target found yet). Chapter 3 introduces nullable types. The following snippets are independent alternatives.
The first uses a Boolean flag:
An inner break cannot exit the outer loop, so the outer loop must check the flag. With deeper nesting, these additional checks multiply.
The second uses goto:
goto jumps straight to a label outside the loop, eliminating the flag. However, the reader has to locate that label to follow the control flow.
Labeled break and continue
C# 15 introduces labeled jump statements (labeled break and continue). Place a label before a loop to let an inner break or continue specify which loop it targets.
Keep the same search criteria and use a labeled break:
All three approaches find the same first target; if none is found, targetPosition is null. The new break searchLoop; exits the labeled outer loop directly, without a flag or a separate label outside the loop.
Now add a search rule: when we encounter an obstacle (IsObstacle is true), skip the remaining cells in that row and move on to the next row. Print a completion message only when the entire row has been scanned without finding a target or encountering an obstacle.
On encountering an obstacle, continue searchLoop; advances the outer loop to its next iteration, skipping the remaining cells and any remaining statements in the outer loop body, including the message. If there is no work after the inner loop, an ordinary break also suffices to skip the remaining cells in a two-level loop. A labeled continue is particularly useful when we also need to skip outer-loop statements or have more nesting levels.
The example project compares the three search methods on the same grid, then demonstrates the obstacle rule.
Source code: DemoLabeledJumps
Note
- A labeled
breakcan target an enclosing loop orswitch; a labeledcontinuecan target only an enclosing loop.- The label must directly label the target loop or
switch. An ordinary labeled block cannot be a jump target.- If searching is a separate operation, consider extracting it into a method and returning as soon as the target is found. There is no need to retain complicated nested loops just to use the new syntax.
Summary
var: The compiler infers the local variable type while retaining static type checking. Useful when a type is obvious, lengthy, or cannot be named (anonymous types). Collection expressions require a target type.dynamic: Defers type checking to runtime, trading type safety for flexibility. Prefer static typing in general; considerdynamicfor legacy COM interop or dynamic structures.- Collection expressions: Use
[...]to initialize arrays,List<T>,Span<T>, and similar collection types in a uniform way;..spreads an existing sequence; C# 15 introduceswith(...)syntax to pass constructor arguments such as capacity and custom comparers. - Object and collection initializers: Set initial values while creating objects/collections.
- Auto-implemented properties: Reduce boilerplate by letting the compiler generate backing fields.
- The
fieldkeyword (C# 14): Access the backing field inside accessors while keeping auto-property syntax. - Anonymous types: Temporary data containers, often used in LINQ.
- String interpolation and raw strings: String interpolation uses
$to embed expressions, while raw strings use"""to preserve multi-line text and special characters; the two can also be combined. - Tuples: A lightweight way to return multiple values, with deconstruction and discards. Consider a named type for long-lived public contracts or encapsulated behavior.
- Labeled jump statements (C# 15): Label loops and use
break <label>orcontinue <label>from inner loops for precise control over outer-loop control flow.
In the next chapter, we’ll explore one of the most important safety features in modern C#: null safety.
Glossary
| Term | Description |
|---|---|
| Anonymous type | A compiler-generated unnamed type; useful for temporary data containers (especially in LINQ). |
| Auto-implemented property | A property whose backing field is generated by the compiler. |
| Backing field | The private field that actually stores a property’s value. |
| Collection expression | C# 12 syntax that uses [...] to initialize arrays, List, Span, and other collection types. |
| Collection expression argument | C# 15 syntax (with(...)) for passing arguments like capacity or comparers inside collection expressions. |
| Collection initializer | Syntax for adding elements while creating a collection. |
| Deconstruction | Splitting a value into multiple variables (often with tuples). |
| Discard | Using _ to ignore a value you don’t care about. |
| Dynamic typing | Using dynamic to defer type checking to runtime. |
field keyword |
A C# 14 feature that lets you access an auto-property’s backing field inside an accessor. |
| Format string | A string that specifies formatting (for example C2). |
| Implicitly typed variable | A local declared with var, with its type inferred by the compiler. |
| Index initializer | C# 6+ syntax for initializing collection elements via indexers. |
| Labeled break / continue | C# 15 feature allowing loop labels to precisely control breaking out of or advancing outer loops. |
| Object initializer | Syntax for setting property values while creating an object. |
| Projection initializer | Syntax that projects existing properties/locals into an anonymous type. |
| Spread syntax | Using .. inside a collection expression to expand the elements of an existing sequence. |
| String interpolation | $"...{expr}..." syntax for embedding expressions into strings. |
| Syntactic sugar | Syntax that doesn’t add new capabilities, but makes code easier to write/read. |
| Tuple | A lightweight structure for grouping values, often used for multi-value returns. |