Some may wonder what is the difference between ValueTuple and Tuple that was released in C# 7, and you might say I have been using Tuples for a while now. Whats the difference? Some of you will remember with code like below that showcase the use of ValueTuple since .NET Framework 4.7
1 2 3 4 5 6 7 |
public Tuple<string, string> GetUserName(int userid) { var firstname = db.GetFirstname(userid); var lastname = db.GetLastname(userid); return new Tuple(firstname, lastname); } |
In order to use this, you will use the data members, such as Item1, Item2, etc., which are fields rather than properties. So in your code it will look something like below. As you can see it pretty ugly and which one is firstname and which one is lastname? You will have to guess was it Item1 or Item2?
1 2 3 |
var username = GetUserName(5); Console.WriteLine($"{username.Item1} {username.Item2}"); |
Main differences
The main difference between Tuple and ValueTuple are:
- System.ValueTuple are structures (value types) rather than classes (reference types). This is meaningful when talking about allocations and Garbage Collection pressure.
- System.ValueTuple are mutable rather than read-only. That is, the value of tuple components can change.
- System.ValueTuple exposes data members, such as Item1, Item2, etc., are fields rather than properties.
Lets try to use the same example and use System.Tuple rather and see how our code changes.
1 2 3 4 |
public (string firstname, string lastname) GetUserName(int userid) { return (firstname: db.GetFirstname(userid), lastname: db.GetLastname(userid);); } |
In the above code you can see it’s shorter and clearer of the intention of the code and when we try to consume this code like below we can use the labels rather.
1 2 3 4 5 6 7 |
var username = GetUserName(5); Console.WriteLine($"{username.Firstname} {username.Lastname}"); //Alternatively var (firstname, lastname) = GetUserName(5); Console.WriteLine($"{firstname} {lastname}"); |
Summary
Hope you learned something new today and start using the new syntactic sugar that C# 7 provides, and if you are doing machine learning you will also feel the benefit of C# Tuples. More on machine learning in later blog post 🙂
Leave A Comment