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

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?

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.

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.

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 🙂