Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions _rules/2225.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
rule_id: 2225
rule_category: dotnet-framework-usage
title: Use deconstruction to simplify variable assignments
severity: 3
---
C# supports deconstructing tuples, records, and any type that defines a `Deconstruct` method. Use this to avoid intermediate variables and make the intent of your code clearer.

Instead of:
Comment thread
dennisdoomen marked this conversation as resolved.

```csharp
public record Point(int X, int Y);

Point point = GetOrigin();
int x = point.X;
int y = point.Y;
```

write:

```csharp
(int x, int y) = GetOrigin();
```

Similarly, deconstruct arrays and collections with pattern matching to avoid index-based access:

```csharp
if (items is [int first, int second, ..])
{
// use first and second directly
}
```

**Tip:** Deconstruction also works in `foreach` loops:

```csharp
foreach ((int key, int value) in dictionary)
{
Console.WriteLine($"{key}: {value}");
}
```