C# 4.0 Tuple Example

C# 4.0 Tuple Example

Tuple is a class in c#.net 4.0. It is used to store any type of data in it. The values assigned to Tuple can’t be changed. Let’s see simplest example of Tuple in C#.net 4.0.

Tuple Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleDemo.App
{
    class Program
    {
        static void Main(string[] args)
        {

            var tuple = new Tuple(12, "Test 1", 150);

            Console.WriteLine(tuple.Item1);
            Console.WriteLine(tuple.Item2);
            Console.WriteLine(tuple.Item3);

            Console.ReadLine();

            
        }

    }
}

Output

12
Test 1
150

When to use Tuple in .net 4.0

You can gropu multiple values in to one single variable. It’s very useful to return as function value instead of using ref or out keyword.

Below Tuple example show usage of Static method Create.

namespace ConsoleDemo.App
{
    class Program
    {
        static void Main(string[] args)
        {

            var tuple = GetSomeValueFromTuple();

            Console.WriteLine(tuple.Item1);
            Console.WriteLine(tuple.Item2);
            Console.WriteLine(tuple.Item3);

            Console.ReadLine();

        }

        public static Tuple GetSomeValueFromTuple()
        {
            var t1 = Tuple.Create(13, DateTime.Now, 3319);
            return t1;
        }

    }
}

Output

13
1/30/2013 9:12:58 PM
3319

Note: You can create pass n number of different data types to Tuple constructor. You can’t modify the values assigned to tuple.

C# MemoryStream ExampleC# XML XmlReaderC# Recursion ExampleC# Do While Loop ExampleDateTimeTryParse using C# and VB.net exampleC# HtmlTextWriter ExampleC# foreach loopC# File.ReadLines() .net 4.0One dimensional array example C#.net VB.netC# Get Random Item From List (VB.net) Example.C# For Loop

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.