0
0
CsharpHow-ToBeginner · 3 min read

How to Use Tuple in C#: Syntax and Examples

In C#, you can use Tuple or the simpler ValueTuple to group multiple values into one object. Use syntax like (int, string) myTuple = (1, "apple"); to create and access tuple elements by position or name.
📐

Syntax

A tuple groups multiple values into a single object. Use (type1, type2, ...) to declare a tuple type. Assign values with (value1, value2, ...). You can name elements for clarity.

  • Tuple type: (int, string) means a tuple with an int and a string.
  • Tuple value: (1, "apple") assigns values.
  • Named elements: (int id, string name) lets you access by id or name.
csharp
var myTuple = (id: 1, name: "apple");
int number = myTuple.id;
string fruit = myTuple.name;
💻

Example

This example shows how to create a tuple, access its elements by position and name, and print them.

csharp
using System;

class Program
{
    static void Main()
    {
        var fruit = (id: 1, name: "apple", price: 0.5);
        Console.WriteLine($"ID: {fruit.id}");
        Console.WriteLine($"Name: {fruit.name}");
        Console.WriteLine($"Price: ${fruit.price}");

        // Access by position
        Console.WriteLine($"First item: {fruit.Item1}");
    }
}
Output
ID: 1 Name: apple Price: $0.5 First item: 1
⚠️

Common Pitfalls

Common mistakes include confusing Tuple and ValueTuple, forgetting to name elements for clarity, or trying to modify immutable Tuple elements. Also, avoid using Tuple when ValueTuple is simpler and more efficient.

Legacy Tuple uses Item1, Item2 without names and is immutable. ValueTuple supports naming and is mutable.

csharp
/* Wrong: Using Tuple without names and trying to modify */
var oldTuple = Tuple.Create(1, "apple");
// oldTuple.Item1 = 2; // Error: Tuple is immutable

/* Right: Use ValueTuple with names */
var newTuple = (id: 1, name: "apple");
newTuple.id = 2; // Allowed
📊

Quick Reference

ConceptSyntax / Description
Declare tuple(int, string) myTuple = (1, "apple");
Named elements(int id, string name) = (1, "apple");
Access by namemyTuple.id or myTuple.name
Access by positionmyTuple.Item1 or myTuple.Item2
Immutable TupleSystem.Tuple (use for older code)
Mutable ValueTupleSystem.ValueTuple (recommended)

Key Takeaways

Use ValueTuple syntax (e.g., (int, string)) for simple, named tuples in C#.
Access tuple elements by name or position using .name or .Item1 properties.
Avoid legacy Tuple class unless needed for compatibility.
Tuples group multiple values without creating a class or struct.
Remember ValueTuple elements can be mutable, unlike Tuple.