Hey there 👋🏻
We got an interesting topic today, and that is a quite unique data structure, that goes by the name Tuple.
So, what is a tuple? 🤔
A tuple is a data structure used to group values that are related to each other into one object, it's often referred to as a single set of data, like a group of things that correlate to one another.
The definition is quite fuzzy and vague, but don't worry, we'll walk through everything you need to know to understand and start using tuples in C#.
Why tuples are useful 🦾
You know that a method in C#, or many other programming languages, could either return nothing, void in the case of our context, or return a value of some type that you the programmer decide on, it could be an int
, double
or even a user-defined type like an Employee
.
If we want our method to return multiple values to us, we could use out parameters, we could make our return type void
, and use the out keyword and get those values from our method later, but forget about that, we can do better. 🤓
Firstly, we look at how we can create and use tuples in C#, before moving on to seeing tuples as return types, and method parameters, so, Let's get going! 🚀
How do we create a Tuple in C#? 📁
Tuples have a sort of unique syntax, but you can follow this blueprint as a template for creating tuples:
(var1, var2, var3, var4, ...) NAME = (value1, value2 value3, value4, ...);
A code example could be:
(int, int, string) values = (1, 34, "Hello World!");
Each value in the tuple is called an Item, and each Item has a number based on how they sequentially appear in order in the tuple, in the previous example, 1 is Item1
and 34 is Item2
and lastly Hello World! is Item3
.
We haven't provided names for our items, thus we get to access them using Item1 Item2 etc..., but we could give them names so that it's easier to access them instead of having a confusion trying to follow along items based off of their numbers, when you provide a name, you get to have two options, either access by the name, or the default Item, but it's more preferable to provide names to the values, like this:
(int num1, int num2, string message) values = ...
How do we access items in a tuple
The syntax here is so simple, just use the name of your tuple, followed by a dot and then the item, like Item1
, Item2
, or, if you've given names for each item, you can use that instead, like the following:
Console.WriteLine(values.message);
//OUTPUT: Hello World!
Ok now that we got the basics out of the way, let's start using Tuples in some cool ways!
Let's build a method that performs primitive operations on two numbers 🧮
We'll see how we can use tuples, to return 4 different values from a method.
Let's Go 🚀
I want to write a method, that takes in two numbers of type double
, and perform the essential arithmetic operations on, Addition, Subtraction, Multiplication & Division, I want my method to return the result of each operation on my numbers.
1: Create two double variables 🔢
Simple enough, we need two numbers to work with, I'll go with these two:
double first = 5;
double second = 10;
2: Create the method that will do the operations 📑
Now here's where it gets interesting, the normal syntax to return maybe the sum of two numbers from a method, would be like this:
static int SumTwoNumbers(int num1, int num2)
{
return num1 + num2;
}
⚠️ Note: I'm assuming you're using a Console application, hence the use of the static keyword, since we want to call this method inside
Main
, which can only invoke static methods.
Enter our first tuple:
static (double Sum, double Subtraction, double Multiplication, double Division) OperateOnTwoNumbers(double num1, double num2)
{
// method code goes here
}
Ok, that's our tuple, notice we have a group of values to return, surrounded by parenthesis, that's the power of tuples, now when we return, we can return a whole bunch of values that we can later on access in a very elegant way, come on now, let's see how we can return them.
Add the following code inside of the previously defined method OperateOnTwoNumbers
double sum = num1 + num2;
double subtraction = num1 - num2;
double multiplication = num1 * num2;
double division = num1 / num2;
return (sum, subtraction, multiplication, division);
Isn't it pretty straightforward?
In case you didn't catch up, I'll explain it to you.
We're creating 4 new variables, each one corresponds to the operation we want to perform, after that, we're returning the result of each operation, bare in mind the initial order, like remember we had Addition, Subtraction..., when you return the values, we don't want to mix things up, and return the subtraction result as the multiplication.
⚠️ Note: We could've done the operations inside the return statement, but it would've looked terribly chaotic and lengthy.
3: Build a string to print the results to the console 📟
We now want to see the results in the console, we want to know if our operations did in fact work or not, we'll use the WriteLine()
statement to format the result, just as follows:
Console.WriteLine($"{first} + {second} = {arithmeticResults.Sum}\n" +
$"{first} x {second} = {arithmeticResults.Multiplication}\n" +
$"{first} / {second} = {arithmeticResults.Division}\n" +
$"{first} - {second} = {arithmeticResults.Subtraction}");
// OUTPUT
5 + 10 = 15
5 x 10 = 50
5 / 10 = 0.5
5 - 10 = -5
Amazing 🌟
You've now seen how we can return various values from a method, additionally, the values to return inside a tuple could be of any type you like, you can return a mix of Integers, Strings, Doubles or whichever type that fits the purpose!
Simple exercise ✍️
💡 Can you think of a method that could make use of returning a group of values, in case you thought of any, write your own implementation and use tuples just like we've done, and post it down in the comments so I can see your work.
In case you haven't found any idea, why don't you try the following:
👀 Can we create a method that takes in a bill, like any amount of money, say 50$, and returns values such as Tip Value, Date of Issuing, Sale Tax? Those values could be arbitrary values, but try to implement that, and attempt creating a receipt-like output in the console!
We saw how we can return multiple values from a method, but guess what, we could also provide multiple parameters to a method, as one parameter only, using Tuples. Let's take a quick look.
Calculate the price of purchased fruits 🍏🍈🍌
Say I went to the market, and bought 5 Apples, 1 melon, and 10 Bananas, and I want to create a method, that takes the numbers of how many pieces of each fruit I bought, multiply the pieces by a price (Imaginary price defined within the method), and return to me the total I should pay.
To do that normally, we could create a method with 3 parameters, one for apples, one for melons, and one for bananas, but why do that when we can pass one tuple instead, let's see how:
static float CalculateTotal((int Apples, int Melons, int Bananas) items)
{
float pricePerApple = 1.25F;
float pricePerMelon = 2.39F;
float pricePerBanana = 1.15F;
float total = (items.Apples * pricePerApple) + (items.Melons * pricePerMelon) + (items.Bananas * pricePerBanana);
return total;
}
The method is pretty much self-explanatory and doesn't require further simplification, if I now call it while passing in a tuple, I should get my total calculated:
(int apples, int melons, int bananas) fruitsPurchased = (5, 1, 10);
float myTotal = CalculateTotal(fruitsPurchased);
Console.WriteLine($"Your total comes out to: {myTotal}$");
//OUTPUT: Your total comes out to: 20.14$
After learning that, could we go back to the exercise I've given you, and instead of only returning the values as a tuple, change the input from the simple bill, to say different prices of dishes you've ordered at a restaurant, pass them as a tuple to the method, and return the Total, Sale Tax, Tip (Assume the tip is 7.5% of the total), could we do that? And remember, show me your work in the comments section down below! 🗂️
Top comments (0)