1. C# Tuple Introduction
In C# if we want to group data which is based on different data types, we can use Tuples. C# provides Tuples class in System namespace. In this example, first we create a Tuple and access its elements. Then, we create function that returns a tuple.
2. Creating C# Tuple
In the below code, we create a Tuple to store the weekdays. Here, our example shows storing only the string datatypes. Bur in tuples, we can even store different data types.
Createstatic method in the tuple class can create the tuples. Here, we created a tuple to store seven data which represents a weekday. Variable
WeekDays1stores the tuple which we created. Note, the data type here is var which stands for variant.
- Once Tuples are created, we can refer the members using
Item2and so on. Item1 represents first item in the tuple and Item2 represents second item in the tuple. In our example, we used this notation & printed Tuesday and Saturday in the console window.
3. Function Returning a C# Tuple
In the previous section, we saw how to create Tuple and access its members. Now, we will create a function which returns a tuple to the caller. Have a look at the example below:
- Here we create a function
GetDayswhich will return seven days of a week in separate compartments as a tuple. In the return type, we placed seven strings and named each string so that caller can make use of those names in stead of using Item1, Item2 etc.
- Here, we return tuple created on the fly. The Tuple represents the weekdays spelled in three letters.
- As like simple function call, we are calling the function GetDays which returns a tuple, and we store that in a variant type of variable
- In the console output, we access some sample weekdays and printing it. Instead of referring the tuple members as Item1, Item2, here we use the more meaningful names Day2 and Day6.
The above function call may give you compile time error if visual studio is not at correct dotnet framework. Make sure you set the Target Runtime as dot net framework 4.7 or above. Refer the below screen:
Error CS1879states that Tuple is not recognized the way we use it.
- Here, the settings under the application group shows that Target Framework is set as ‘.Net Framework 4.7’. Now, the compilation goes smooth without the Error CS1879.
4. C# Tuples Completed Code & Output
static void Main(string args)
//Sample 01: Create a Tuple
var WeekDays1 =
Tuple.Create("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
//Sample 02: Access Tuple and Print It
//Sample 04: Use the Function to return the Tuple
var WeekDays2 = GetDays();
//Sample 03: Create a Function for Tuple
static (string day1, string day2, string day3,
string day4, string day5, string day6,
string day7) GetDays()
return ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");