Limited Offer
60% OFF on all plans!

Tuples & Deconstruction in C#

Return multiple values from methods using ValueTuple, name tuple elements for clarity, deconstruct tuples into variables, and discard unwanted values with _ discards.

Creating Tuples

1. Unnamed Tuples

Group multiple values with `(value1, value2)` — elements accessed as `Item1`, `Item2`.

2. Named Tuples

Give elements meaningful names — access them by name instead of Item1/Item2.

Tuples as Return Values

1. Returning Multiple Values

Use a tuple return type to cleanly return several related values.

Tuple Deconstruction

1. Basic Deconstruction

Use `var (a, b) = tuple` to unpack a tuple into named variables.

2. Discarding Elements with _

Use `_` to ignore tuple elements you do not need.

3. Deconstruction in foreach

Deconstruct tuples directly inside a foreach loop.

Tuple Equality

1. Comparing Tuples

Two tuples are equal if all their elements are equal — element names don't matter.

Deconstructing Custom Types

1. Adding Deconstruct() to a Class

Any class with a `Deconstruct` method can be used with `var (a, b) = obj`.

2. Deconstruct as Extension Method

Add deconstruction to a type you don't own via an extension method.

Object Destructuring

1. Basic Destructuring

Unpack an object's properties into local variables via deconstruction.

2. Renaming on Destructure

Use different variable names when deconstructing to avoid conflicts.