.NET Core's Tuple, a struct offering a-group of elements, is an incredibly useful feature with a plethora of applications. If you're wondering how to leverage it effectively, stick around as we explore a comprehensive, real-world example.

Tuples in .NET Core are perfect for returning multiple values from a method or function. They're value types that provide a convenient way to group and manipulate elements of various types.

.NET Core Tuple: Basics & Key Features
Before we dive into an example, let's quickly cover the basics. Tuples in .NET Core are tuples of values, and they're part of the System.Tuple namespace. They can hold between 1 and 7 values of any type.

Key features include immutability, named and unnamed elements, and pattern matching for easier consumption.
Tuple Creation & Initialization

Tuples can be initialized in a few ways. Here's a simple example:
var myTuple = Tuple.Create("Hello", 10);
Or, you can explicitly declare the item types:
var myTuple = Tuple<string, int>("Hello", 10);
Tuple Deconstruction

To access tuple elements, use indexers (Item1, Item2, etc.) or, for comfort, deconstruct the tuple:
(string value, int count) = myTuple;
Console.WriteLine(value); // "Hello"
Console.WriteLine(count); // 10
Real-World Example: Returning Multiple Values
Tuples shine when returning multiple values from a method. Suppose we have a function that performs calculations and returns two results:

Calculating Discount & New Price
Here's a function that calculates the discount amount and the new price after discount:









public (decimal OriginalPrice, decimal Discount, decimal NewPrice) CalculateDiscount(decimal originalPrice, decimal discountPercentage)
{
decimal discountAmount = originalPrice * (discountPercentage / 100);
decimal newPrice = originalPrice - discountAmount;
return (originalPrice, discountAmount, newPrice);
}
The function returns a tuple containing the original price, discount amount, and the new price.
Consuming the Tuple
Now, let's consume the tuple and display the results:
decimal price = 100.00m;
decimal discountPercentage = 20.00m;
var results = CalculateDiscount(price, discountPercentage);
Console.WriteLine($"Original Price: ${results.Item1:N2}");
Console.WriteLine($"Discount: ${results.Item2:N2}");
Console.WriteLine($"New Price: ${results.Item3:N2}");
Using tuples makes the code clean and easy to understand. It's obvious that the function returns three values, and their names are intuitive. This way, we avoid creating a custom class or struct just to group these values.
Whether you're returning multiple values from a method or grouping values for analysis, .NET Core's tuples are a powerful, flexible, and elegant feature. So, next time you're looking to return multiple results, consider using tuples!