Skip to main content

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:

var scores = new Dictionary<string, int>();
Dictionary<string, int> scores = new();

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:

var result = GetData();      // What type is result?
Customer result = GetData(); // Clear at a glance

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:

var s1 = "hello";      // (1)
dynamic s2 = "hello";  // (2)
int i = s1;            // (3)
int j = s2;            // (4)
  1. The compile-time type is string, and the runtime type is also string.
  2. The compile-time type is dynamic, while the runtime type is string.
  3. This fails at compile time: Cannot implicitly convert type string to int.
  4. This fails at runtime: Cannot implicitly convert type string to int.

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 s1 = "hello";
var v = s1;            // Compile-time type is dynamic
int i = v;             // Runtime error!

dynamic x = 2;
var y = x * 10;        // Compile-time type is dynamic
var z = (int) x;       // Compile-time type is int

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:

public string GetFullName(dynamic obj)
{
    return obj.FirstName + " " + obj.LastName;
}

public void Test()
{
    dynamic obj = new ExpandoObject();
    obj.FirstName = "Bruce";
    obj.LastName = "Wayne";
    var fullName = GetFullName(obj); // "Bruce Wayne"
}

Notes:

  • dynamic obj = new ExpandoObject();: If you want to use dynamic member syntax such as obj.FirstName = ..., the variable’s compile-time type must be dynamic. If you change it to var obj = new ExpandoObject();, the code still compiles, but the compile-time type becomes ExpandoObject, so the later dynamic member access will no longer compile.
  • obj.FirstName = "Bruce"; and obj.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:

var obj = new { FirstName="Bruce", LastName="Wayne" };
var fullName = GetFullName(obj);

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> or ReadOnlySpan<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:

int[] numbers = new int[] { 1, 2, 3 };
List<string> strings = new List<string> { "A", "B", "C" };

With collection expressions, you can use a single form:

int[] numbers = [1, 2, 3];
List<string> strings = ["A", "B", "C"];

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.

int[] section1 = [1, 2];
int[] section2 = [5, 6];

int[] allLevels = [0, .. section1, 3, 4, .. section2, 7];
// Result: [0, 1, 2, 3, 4, 5, 6, 7]

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.

void PrintTags(string[] tags)
{
    foreach (var tag in tags)
        Console.WriteLine(tag);
}

PrintTags(["C#", ".NET", "Coding"]);

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.

void PrintNumbers(params IList<int> numbers) // Requires C# 13 / .NET 9+
{
    foreach (var n in numbers)
        Console.WriteLine(n);
}

// All three calls are valid
PrintNumbers(1, 2, 3);
PrintNumbers([1, 2, 3]);
PrintNumbers(new List<int> { 1, 2, 3 });

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.

int[] emptyArray = [];
List<string> tags = [];

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.

ReadOnlySpan<byte> header = [0xDE, 0xAD, 0xBE, 0xEF];

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:

HashSet<string> tags =
    new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
    "C#", "c#", "dotnet"
};

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:

HashSet<string> tags =
    [with(StringComparer.OrdinalIgnoreCase), "C#", "c#", "dotnet"];

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:

string[] items = ["alpha", "beta", "gamma"];
List<string> names = [with(capacity: items.Length * 2), .. items];

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, the with(...) arguments are passed to that method before its final ReadOnlySpan<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 compile

The 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];  // OK

This 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:

var scores = new Dictionary<string, int>
{
    ["Alice"] = 95,
    ["Bob"] = 87
};

However, if you only need to represent an empty dictionary, you can still write:

Dictionary<string, int> emptyScores = [];

2.4 Object initializers

Object initializers let us set properties when creating an object. Assume Student has two settable properties, Name and Birthday.

var student = new Student
{
    Name = "Alice",
    Birthday = new DateTime(1971, 1, 20)
};

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 Name would typically need a default value, a required modifier, 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:

var s = new Student("Default") { Name = "Alice" };
// s.Name == "Alice"

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:

var students = new List<Student>
{
    new Student { Name = "Alice" },
    new Student { Name = "Bob" }
};

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:

// Constructor parameters have default values
public Student(string name, DateTime? birthday = null) { ... }

// Omit birthday at the call site
var s = new Student("Alice");

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:

public string Name { get; set; } = "";
public string Id { get; private set; } = "";

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:

// C# 13 and earlier
private int _age;

public int Age
{
    get => _age;
    set
    {
        if (value < 0)
            throw new ArgumentOutOfRangeException(
                nameof(value), "Age cannot be negative!");
        _age = value;
    }
}

With the field keyword, you can keep the validation logic while avoiding the private field declaration:

// C# 14: using the `field` keyword
public int Age
{
    get;  // Compiler-generated getter
    set
    {
        if (value < 0)
            throw new ArgumentOutOfRangeException(
                nameof(value), "Age cannot be negative!");

        field = value;  // 'field' is the compiler-generated backing field
    }
}

This approach has a few clear advantages:

  1. Less boilerplate: No private field declaration, and no separate field name to maintain.
  2. Fewer mistakes: Validation and auto-properties can coexist without you having to remember the right field name.
  3. 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:

public class Person
{
    // ✘ Mixing `field` with a manually declared field
    private int _count;
    public int Count
    {
        get => field;
        set => _count = value; // Warning CS9266
    }
}

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.

var emp = new { Name = "Michael", Birthday = new DateTime(1971, 1, 1) };

Console.WriteLine($"Name: {emp.Name}");
Console.WriteLine($"Birthday: {emp.Birthday:yyyy-MM-dd}");

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:

var p1 = new { X = 1, Y = 2 };
var p2 = new { X = 3, Y = 4 };
var p3 = new { Y = 4, X = 3 };
// p1 and p2 have the same type; p3 has a different type.

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:

var p1 = new { X = 1, Y = 2 };
var p2 = new { X = 1, Y = 2 };

Console.WriteLine(p1 == p2);      // False (different references)
Console.WriteLine(p1.Equals(p2)); // True  (all property values match)

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.

var emp = new { Name = "Michael", Age = 50 };
var summary = new { emp.Name, emp.Age };
// Equivalent to new { Name = emp.Name, Age = emp.Age }

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:

var a1 = new { A = 1, B = 2, C = 3 };
var a2 = a1 with { B = 99 };  // Copy a1, but change B to 99

Console.WriteLine($"a2: A={a2.A}, B={a2.B}, C={a2.C}");
// Output: a2: A=1, B=99, C=3

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:

var name = "Michael";
var age = 50;

// Traditional approach (string.Format)
var s1 = string.Format("Name: {0}, Age: {1}", name, age);

// String interpolation
var s2 = $"Name: {name}, Age: {age}";

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:

Console.WriteLine($"Price: {123.456m:C2}");
Console.WriteLine($"Date: {DateTime.Today:yyyy-MM-dd}");
Console.WriteLine($"|{"Jordan",-10}|{95,5}|");

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:

const string Greeting = "Hello";
const string Target = "World";
const string Message = $"{Greeting}, {Target}!"; // Valid in C# 10+

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.

var legacyJson = @"{
    ""name"": ""Michael"",
    ""age"": 50,
    ""path"": ""C:\\Windows\\System32""
}";

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 ("""):

var json = """
    {
        "name": "Michael",
        "age": 50,
        "path": "C:\\Windows\\System32"
    }
    """;

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:

var name = "Michael";
var json = $$"""
    {
        "name": "{{name}}",
        "age": 50
    }
    """;

Console.WriteLine(json);
// Output:
// {
//     "name": "Michael",
//     "age": 50
// }

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:

(string Name, int Age) person = ("Bob", 23);

Console.WriteLine(person.Name); // Bob
Console.WriteLine(person.Age);  // 23

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:

public (double Lat, double Lon) GetCoordinates(string address)
{
    // Pretend we queried a map API
    return (25.0330, 121.5654);
}

var coords = GetCoordinates("Taipei 101");
Console.WriteLine($"Lat: {coords.Lat}, Lon: {coords.Lon}");

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:

var person = ("Alice", 30);

// Deconstruct the tuple into two variables
(string name, int age) = person;

Console.WriteLine(name); // Alice
Console.WriteLine(age);  // 30

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 latitude

This 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:

var person = new Person
{
    Name = "Bob",
    Birthday = new DateTime(1980, 5, 15),
    Email = "bob@example.com"
};

// Implicitly calls the first Deconstruct
var (name, birthday) = person;

// Implicitly calls the second Deconstruct
var (fullName, dob, email) = person;

Source code: DemoTupleDeconstruction

Design guidelines:

  • Deconstruct must return void.
  • Parameters must be out parameters.
  • 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:

bool found = false;
(int Row, int Col)? targetPosition = null;
for (int r = 0; r < rows; r++)
{
    for (int c = 0; c < cols; c++)
    {
        if (grid[r, c].IsTarget)
        {
            targetPosition = (r, c);
            found = true;
            break; // Exits only the inner loop
        }
    }
    if (found)
        break; // The outer loop must check the 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:

(int Row, int Col)? targetPosition = null;
for (int r = 0; r < rows; r++)
{
    for (int c = 0; c < cols; c++)
    {
        if (grid[r, c].IsTarget)
        {
            targetPosition = (r, c);
            goto SearchDone;
        }
    }
}
SearchDone:
Console.WriteLine(targetPosition);

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:

(int Row, int Col)? targetPosition = null;
searchLoop: for (int r = 0; r < rows; r++)
{
    for (int c = 0; c < cols; c++)
    {
        if (grid[r, c].IsTarget)
        {
            targetPosition = (r, c);
            break searchLoop;
        }
    }
}

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.

(int Row, int Col)? targetPosition = null;
searchLoop: for (int r = 0; r < rows; r++)
{
    for (int c = 0; c < cols; c++)
    {
        if (grid[r, c].IsObstacle)
            continue searchLoop;

        if (grid[r, c].IsTarget)
        {
            targetPosition = (r, c);
            break searchLoop;
        }
    }

    Console.WriteLine($"Row {r} was fully scanned");
}

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 break can target an enclosing loop or switch; a labeled continue can 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; consider dynamic for 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 introduces with(...) 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 field keyword (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> or continue <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.