EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

C# Tuples

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » C# Tutorial » C# Tuples

C# Tuples

Introduction to C# Tuples

The C# tuples is a data structure that was introduced in the C#.net version 4.0. The tuple data structure is designed to hold elements that are of different data types. Tuples help in returning multiple values from a class method in a single parameter which has many advantages over Out Parameters, class or structs types, or dynamic return type. As the parameters are passed into a single data set, it becomes easy to access this data set and perform different operations on it.

How to Create C# Tuples?

Tuples can be created in two different ways

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

1. Using Constructor

The constructor for creating the tuple is present in Tuple <T> class. The acronym ‘T’ represents multiple datatype that are specified while creating the tuple. The elements stored in tuple are numbered zero to seven, that is any normal tuple holds only 8 elements and if one tries to enter more than 8 elements, compiler throws an error.

Single Element Tuple

Tuple <T1> (T1)

Example:

Tuple<int> Tuple_example = new Tuple<int>(27);
Console.WriteLine(Tuple_example);
Console.ReadLine();

Output:

C# Tuples-1.1

Multiple Element Tuple

Tuple <T1, T2> (T1, T2)

Example:

Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1, "cat", true);
Console.WriteLine(tuple.Item1);
Console.WriteLine(tuple.Item2.ToString());
Console.ReadLine();

Output:

C# Tuples-1.2

2. Create Method

C# provides a static Create method to create tuple as follows

Single Element Tuple

Create (T1);

Example:

var Tuple_example = Tuple.Create(27);
Console.WriteLine(Tuple_example);
Console.ReadLine();

Output:

C# Tuples-1.3

Multiple Element Tuple

Create (T1, T2);

Example:

var Tuple_example = Tuple.Create(1, "cat", true);
Console.WriteLine(Tuple_example.Item1);
Console.WriteLine(Tuple_example.Item2.ToString());
Console.ReadLine();

Output:

C# Tuples-1.4

While using the constructor, we need to specify the data type of every element while creating the tuple. The Create methods helps us in eliminating the cumbersome coding as shown above.

ValueTuple

The generic tuple is a reference type it means the values are stored on heap, which makes its usage costly in terms of memory and performance. C#7.0 introduced a new and improved version of Tuple over generic tuple and named it as ValueTuple. The ValueTuple is stored on the heap, which is easy to retrieve. The value tuple comes with .NET Framework 4.7 or .NET library 2.0. To separately install the tuple functionality, you need to install the NuGet Package called System.Value.Tuple.

Popular Course in this category
C# Training Program (6 Courses, 17 Projects)6 Online Courses | 17 Hands-on Project | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.6 (8,847 ratings)
Course Price

View Course

Related Courses
ASP.NET Training (8 Courses, 19 Projects).NET Training Program (4 Courses, 19 Projects)

Important points about ValueTuple

  • It is easy to create a ValueTuple

Example:

var Tuple_example = (1, "cat", true);
Console.WriteLine(Tuple_example.Item1);
Console.WriteLine(Tuple_example.Item2.ToString());
Console.ReadLine();

Output:

C# Tuples-1.5

This is equivalent to:

var Tuple_example = Tuple.Create(1, "cat", true);
Console.WriteLine(Tuple_example.Item1);
Console.WriteLine(Tuple_example.Item2.ToString());
Console.ReadLine();

  • The ValueTuple can also be declared without using the ‘var’ keyword. In this case we need to provide the datatype of each member

Example:

(int, string, bool) Tuple_example = (1, "cat", true);
Console.WriteLine(Tuple_example.Item1);
Console.WriteLine(Tuple_example.Item2.ToString());
Console.ReadLine();

Output:

C# Tuples-1.6

  • The values can be returned from a ValueTuple using

Example:

details.Item1;   – returns 28
details.Item2; -- returns ”CBC”

  • The ValueTuple, unlike the normal tuple, cannot contain only one element.

Example:

var detail = (28);  --this is not a tuple
var details = (28, “CBC”); -- this is a tuple

In the first statement, the compiler will not consider ‘detail’ as a tuple, instead, it will be considered and a normal ‘var’ type.

  • The ValueTuple can hold more than eight values without having to nest another tuple in the seventh position.
  • The properties in the ValueTuple can have different names than Item1, Item2 etc.

(int ID, String Firstname, string SecondName) details = (28, “CBC”, “C# Tuples”);

  • The elements in the ValueTuples can also be separated or discarded, depending on the need of the programming. In the above example, the element ‘FirstName’ can be discarded and a tuple containg first element and third element can be passed as a return type of the method.

How does Tuple Work?

  1. The C# framework allows only eight elements in the tuple, that means we can have values from 0 to 7 and if you want to create a Tuple with more than that, then specify the seventh element TRest as the nested tuple

var nestedtuple_example = new Tuple <int, string, string, int, int, int, string, Tuple<double, int, string>> (5, “This”, “is”, 7,8,9, “number”, Tuple.Create (17.33, 29,”April”));

  1. The one important use of tuple is to pass it as a single entity to the method without using the traditional ‘out’ and ‘ref’ keywords. The use of ‘Out’ and ‘ref’ parameters can be difficult and confusing, also the ‘out’ and ‘ref’ parameters do not work with ‘asnyc’ methods. e.g. public void TupleExampleMethod (Tuple <int, int> tupleexample)

{
Var multiplication = tupleexample.Item1 * tupleexample.Item2;
Console.WriteLine (“Multiplication is”, {0}, multiplication);
}

The to the method TupleExampleMethod would look like

TupleExampleMethod(new Tuple<int, int> (34,56));

  1. The dynamic keyword can also be used to return values from any method, but it is seldom used due to performance issues. The returning of the tuple from a method.

public static Tuple <int, string> GetPerson()
{
return Tuple.Create (1, “abc”);
}

Let’s create a program in Visual to understand how tuple works.

  • Launch Visual Studio and create a windows project.

Output -2.1

  • We are creating a simple multiplication program that shows passing tuples by a method. A sample window created as below.

Output -2.2

The values from both textboxes are taken into a tuple and the tuple is passed on to a method.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnMultiply_Click(object sender, EventArgs e)
{
int value1 = Convert.ToInt32(txtVal1.Text);
int value2 = Convert.ToInt32(TxtVal2.Text);
CallMethod(new Tuple<int, int>(value1, value2));
}
private void CallMethod(Tuple<int, int> tuple)
{
txtResult.Text = Convert.ToString(tuple.Item1 * tuple.Item2);
Console.ReadLine();
}
}
}

The result is displayed in the third text box named as txtResult. End result looks like.

Output -2.3

Conclusion

The tuple data structure is a reference type, which means the values are stored on the heap instead of stack. This makes usage of tuples and accessing them in the program an intensive CPU task. The only 8 elements in tuples property is one of the major drawbacks of tuples as nested tuples are more prone to induce ambiguity. Also accessing elements in tuple with Item<number> is also ambiguous as one must remember what position the element is on in order to access it. C#7 has introduced ValueTuple which is value type representation of tuple. It works only on .NET Framework 4.7 and hence needs to install separately from the Nuget package System.ValueTuple package.

Recommended Articles

This is a guide to C# Tuples. Here we also discuss the Introduction and how to create c# tuples along with examples and its code implementation. You may also have a look at the following articles to learn more –

  1. C# Versions
  2. C# SortedDictionary
  3. C# Lambda Expression
  4. Assert in C#

C# Training Program (6 Courses, 17 Projects)

6 Online Courses

17 Hands-on Project

89+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C sharp Tutorial
  • Advanced
    • Inheritance in C#
    • Exception Handling in C#
    • Types of Exception in C#
    • C# FileNotFoundException
    • C# NullReferenceException
    • C# OutOfMemoryException
    • C# StackOverflowException
    • Custom Exception in C#
    • What is Multithreading in C#
    • C# finally
    • C# System.IO
    • What is StringBuilder in C#
    • DataReader C#
    • BinaryWriter in C#
    • C# BinaryReader
    • TextWriter in C#
    • TextReader in C#
    • C# StringReader
    • C# StringWriter
    • C# StreamReader
    • C# StreamWriter
    • C# FileInfo
    • What is Design Pattern in C#?
    • Multithreading in C#
    • Sorting in C#
    • Bubble Sort in C#
    • C# SortedList
    • C# SortedSet
    • C# SortedDictionary
    • Abstract Class in C#
    • Access Modifiers in C#
    • C# Generics
    • Deserialization in C#
    • C# Thread
    • C# Thread Join
    • C# Thread Sleep
    • C# Thread Synchronization
    • C# Class
    • Sealed in C#
    • Sealed Class in C#
    • Polymorphism in C#
    • C# Call By Reference
    • Virtual Keyword in C# 
    • Yield Keyword in C#
    • Regular Expression in C#
    • C# Lambda Expression
    • C# Predicate
    • Convert Object to JSON C#
    • Checkbox in C#
    • C# MessageBox
    • Collections in C#
    • List in C#
    • C# LinkedList
    • Listbox in C#
    • Protected in C#
    • C# EventHandler
    • Private in C#
    • this Keyword in C#
    • Static Keyword in C#
    • C# Out Parameter
    • Assert in C#
    • C# Delegates
    • C# Interface
    • Generics in C#
    • Timer in C#
    • C# Serialization
    • Metadata in C#
    • C# Stack
    • C# Using Static
    • Queue in C#
    • C# File.Exists
    • C# Tuples
    • C# Create JSON Object
    • Partial in C#
    • C# readonly
    • C# Action Delegate
    • C# Await Async
    • C# Dictionary
    • IEnumerable C#
    • C# Data Grid View
    • C# Dynamic
    • Web Services in C#
    • C# Pattern Matching
    • C# Extension Methods
    • C# XmlSerializer
  • Basic
    • Uses Of C#
    • C# Versions
    • C# Data Types
    • Variables in C#
    • Namespaces in C#
    • C# Compilers
    • C# Keywords
    • Iterators in C#
    • Objects in C#
    • C# Object Dispose
    • C# object to XML
    • C# check object type
    • C# Object Serialization
    • Pointers in C#
    • C# Literals
    • C# Commands
    • C# Custom Attribute
    • Type Casting in C#
    • String vs String C#
    • C# Struct vs Class
  • Operators
    • Logical Operators in C#
    • Conditional Operators in C#
    • Bitwise Operators in C#
    • C# OR Operator
    • C# Ternary Operators
    • Operator Precedence in C#
  • Control Statement
    • C# if Statement
    • Else If in C#
    • Continue in C#
    • Break in C#
    • Switch Statement in C#
    • Goto Statement in C#
  • Loops
    • C# For Loop
    • C# While Loop
    • C# do-while loop
    • C# foreach Loop
  • Arrays
    • Arrays in C#
    • 2D Arrays in C#
    • C# Jagged Arrays
    • String Array in C#
    • C# Multidimensional Arrays
  • Constructor and Destructor
    • Constructor in C#
    • Copy Constructor in C#
    • Static Constructor in C#
    • Destructor in C#
  • overloading and overrideing
    • Overloading and Overriding in C#
    • Overloading in C#
    • Overriding in C#
    • Method Overloading in C#
    • Method Overriding in C#
    • Operator Overloading in C#
  • Functions
    • C# Functions
    • C# String Functions
    • Math Functions in C#
    • Recursive Function in C#
    • C# Anonymous Functions
    • C# Local Functions
    • Enum in C#
    • Trim() in C#
    • clone() in C#
    • C# random
    • C# String Format()
    • C# String Interpolation
    • C# StartsWith()
    • C# String IndexOf()
    • DateTime in C#
    • C# Nullable
    • C# nameof
    • C# checked
    • C# String PadLeft
    • Convert String to Double in C#
    • Convert int to String C#
    • String to Date C#
    • C# intern()
    • C# Stopwatch
    • C# DirectoryInfo
    • C# Compare()
    • C# Base
    • C# SOAP
    • Lock in C#
  • Programs
    • Patterns in C#
    • Swapping in C#
    • Palindrome in C#
    • Factorial in C#
    • Fibonacci Series in C#
    • Random Number Generator in C#
    • Prime Numbers in C#
    • Armstrong Number in C#
    • Reverse String in C#
  • Interview questions
    • C# Interview Questions and Answers
    • C# OOP Interview Questions
    • C# Design Pattern Interview Questions

Related Courses

C# Certification Training

ASP.NET Course

.NET Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C# Training Program (6 Courses, 17 Projects) Learn More