Tuples in C#

In C# tuples allow us to store data of various types in a tuple object. Tuple is also useful in returning multiple values from a function.

Here is a complete example of tuple:

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

namespace ConsoleApplication8
{
    class Program
    {        
        static void Main(string[] args)
        {

            Tuple<int, int> tuple1 = Tuple.Create<int, int>(10, 20);
            Tuple<int, string, double> tuple2 = Tuple.Create<int, string, double>(10, "pakistan", 44.5);

            // Console.WriteLine(tuple1);
            //  Console.WriteLine(tuple2);
            // Console.WriteLine(tuple2.Item1);
            // Console.WriteLine(tuple2.Item2);
            // Console.WriteLine(tuple2.Item3);

            //Tuple<int, Tuple<int, int>, int> tuple3 = Tuple.Create<int, Tuple<int, int>, int>(400, Tuple.Create<int, int>(10, 20), 500);

            //Console.WriteLine(tuple3);
            //Console.WriteLine(tuple3.Item1);
            //Console.WriteLine(tuple3.Item2);
            //Console.WriteLine(tuple3.Item3);
            //Console.WriteLine();
            //Console.WriteLine(tuple3.Item2.Item1);
            //Console.WriteLine(tuple3.Item2.Item2);

            //Console.WriteLine();

            //Tuple<int,string,double> t = GetData();

            //Console.WriteLine("{0}, {1}, {2}",t.Item1, t.Item2, t.Item3);

            Tuple<Student> s = GetStudent();
            Console.WriteLine(s.Item1.name);

        }    
        
        static Tuple<int,string,double> GetData()
        {
            Tuple<int, string, double> tuple = Tuple.Create<int, string, double>(12, "abbottabad", 5.6);

            return tuple;
        }

        static Tuple<Student> GetStudent()
        {
            Tuple<Student> tuple = Tuple.Create<Student>(new Student());

            return tuple;
        }

    }

    class Student
    {
        public string name;

        public Student()
        {
            name = "ali";
        }
    }
}

 

Tags:,

Add a Comment

Your email address will not be published. Required fields are marked *