Tuple Class in C#

Introduction

This article demonstrates different scenarios of using Tuple Class in C# .This was quite new to me which I practiced recently.
 
I was developing a demo application which was supposed to return multiple list Items. To bind each ListItems to respected ComboBox  I have to use 2 separate methods as one method had only one return type. To compress my code I then used Tuple Class.
 
See the below example where the 2nd one was the application I was developing.
 
Description
 
It is included in .NET 4.0+'s Tuple
 
Example-1(Add and Multiply 2 value)
  1. static void Main(string[] args)  
  2. {
  3.     int a = 10;
  4.     int b = 20;
  5.     var result = Add_Multiply(a, b);
  6.     Console.WriteLine(result.Item1);
  7.     Console.WriteLine(result.Item2);
  8. }
  9. private static Tuple<intint> Add_Multiply(int a, int b)  
  10. {
  11.     var tuple = new Tuple<intint>(a + b, a * b);
  12.     return tuple;
  13. }
Example-2 (Return List of data in Item wise)
 
Here I am reading data from a text file which contains country name and country code and want to bind the names and code in a ComboBox. Here is the below code
  1. public static Tuple<List<string>, List<string>> GetAllData()  
  2. {  
  3.     List<string> CountryName = new List<string>();  
  4.     List<string> CountryCode = new List<string>();  
  5.     using (var sr = new StreamReader(@"Country.txt")) //using System.IO; //Text file in bin/Debug folder of application
  6.     {  
  7.         string line;  
  8.         while ((line = sr.ReadLine()) != null)  
  9.         {  
  10.             int index = line.LastIndexOf(" ");  
  11.             CountryName.Add(line.Substring(0, index));
  12.             CountryCode.Add(line.Substring(index + 1));
  13.         }  
  14.     }  
  15.     return new Tuple<List<string>, List<string>>(CountryName,CountryCode);

 To bind data in ComboBox
  1. ddlCountryName.ItemsSource = Helper.GetAllData().Item1; //Helper is the class where GetAllData() is written
  2. ddlCountryCode.ItemsSource = Helper.GetAllData().Item2; 
Note
  1.  You can find the attached sample solution for reference which is developed in WPF.
  2. I hope you will love to use Tuple class.

Happy coding :) ;)

Up Next
    Ebook Download
    View all
    Learn
    View all