Navigate to Post

Tuesday, March 31, 2020

Learn C#~#2 Tuples

The Tuples in C# are going to be used when a method is going to return more than one values. Tuple is an ordered sequence of heterogeneous objects.

In the following example, we are calling a method "CalculateTotalSalary" to get total salary for last month for a particular company. here we are making use of tuples, because here we are returning multiple values from this method. we are passing company name to method


using System;
using System.Collections;
using System.Collections.Generic;

namespace MyTestConsole
    class Program
        static void Main()
            string compName = "ABC Corp";
            var (CompName, ForMonth, TotalSalary) = CalculateTotalSalary(compName);
            Console.WriteLine($"{CompName}'s Total salary for month: " +
                $"{ForMonth} is {TotalSalary}");

        private static (string CompName, string ForMonth, double TotalSalary)
            CalculateTotalSalary(string compName)
            Hashtable htSalaries = new Hashtable();
            htSalaries.Add("Jan", 120000.0);
            htSalaries.Add("Feb", 130000.8);
            htSalaries.Add("Mar", 140050.0);
            htSalaries.Add("Apr", 146000.0);
            htSalaries.Add("May", 146950.0);
            htSalaries.Add("Jun", 136950.0);
            htSalaries.Add("Jul", 136950.0);
            htSalaries.Add("Aug", 136950.0);
            htSalaries.Add("Sep", 136954.0);
            htSalaries.Add("Oct", 130050.0);
            htSalaries.Add("Nov", 130850.0);
            htSalaries.Add("Dec", 130950.0);

            string CompName = compName;
            string ForMonth = DateTime.Now.AddMonths(-1).ToString("MMM");
            double TotalSalary = 0.0;
            TotalSalary = (double)htSalaries[ForMonth];

            return (CompName, ForMonth, TotalSalary);



All time trending post