TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
What is a Tuple in C# and When to Use It
Khumana Ram
Apr 26, 2015
40.6
k
0
5
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
In this blog you will learn about tuple in C# programming.
Introduction
Tuple is a generic static class that was added to C# 4.0 and it can hold any amount of elements, and they can be any type we want.
So using tuple, we can return multiple values.One great use of tuple might be returning multiple values from a method.
It provides an alternative to "ref" or "out" if you have a method that needs to return multiple new objects as part of its response.
A tuple allows you to combine multiple values of possibly different types into a single object without having to create a custom class.
This can be useful if you want to write a method that for example returns three related values but you don't want to create a new class.
We can create a Tuple using the Create method.
This method provide to 8 overloads, so we can use a maximum of 8 data types with a Tuple.
Followings are overloads
Create(T1)- Tuple of size 1
Create(T1,T2)- Tuple of size 2
Create(T1,T2,T3) – Tuple of size 3
Create(T1,T2,T3,T4) – Tuple of size 4
Create(T1,T2,T3,T4,T5) – Tuple of size 5
Create(T1,T2,T3,T4,T5,T6) – Tuple of size 6
Create(T1,T2,T3,T4,T5,T6,T7) – Tuple of size 7
Create(T1,T2,T3,T4,T5,T6,T7,T8) – Tuple of size 8
Example
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
EDUDOTNET_TupleDemo
{
class
EDUDOTNET
{
static
void
Main(
string
[] args)
{
//This represents a tuple of size 3 (Create a new 3-tuple, or Triple) with all string type
var tuple = Tuple.Create<
string
,
string
,
string
>(
"EDUDOTNET"
,
"IT"
,
"SOLUTION"
);
Console.WriteLine(tuple);
//This represents a tuple of size 2 (Create a new 2-tuple, or Pair) with int & string type
var tuple1 = Tuple.Create<
int
,
string
>(51,
"CTO-EDUDOTNET"
);
Console.WriteLine(tuple1);
//We can also access values of Tuple using ItemN property. Where N point to a particular item in the tuple.
//This represents a tuple of size 4 (Create a new 4-tuple, or quadruple) with 3 string & 1 int type
var tuple2 = Tuple.Create<
int
,
string
,
string
,
string
>(1,
"Khumesh"
,
"EDUDOTNET"
,
"IT-Solution"
);
Console.WriteLine(tuple2.Item1);
Console.WriteLine(tuple2.Item2);
Console.WriteLine(tuple2.Item3);
Console.WriteLine(tuple2.Item4);
Console.WriteLine(
"Enjoying With Tuple.......... :)"
);
Console.ReadLine();
}
}
}
What is Tuple in C#
When it usetuple
Example of Tuple
Next Recommended Reading
Remove AM PM from Time String using C#