Tuples in c# example step by step

 

In this Part 1 of the article we learn about Tuples which is not new to programming languages but it was new to C# when introduced in C# 4.0. We will see how to use tuples and overcome it by using anonymous types

Scenario where to use Tuples

Consider the following image example where student information data like school name, student name and student roll number which we want to parse it i.e. break it into small piece of details and get it displayed on console prompt as separate variable. On each line which will display all student information separately. Here coding is done using general method to display output on console prompt using arrays, split functions and out variable. These out variable will help to fill in the data into individual variable which are declared under Main method. As our data is student's data which is "St.GeorgeHighSchool Bannie 20" and separated by spaces.

Split function will parse data as per spaces and then it will be pushed into array which will display result of data into individual variable.

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

namespace ConsoleApplication5
{
classProgram
    {
staticvoid Main(string[] args)
        {
string strng = "St.GeorgeHighSchool Bannie 20";
string strSchool = "";
string strStudent = "";
int RollNo = 0;
            PData(strng, out strSchool, out strStudent, out RollNo);
Console.WriteLine("School Name:" + strSchool);
Console.WriteLine("Student Name:" + strStudent);
Console.WriteLine("Roll No.:" + RollNo.ToString());
Console.ReadLine();
        }

staticvoid PData(string strngData, outstring strSchool, outstring strStudent, outint RollNo)
        {
string[] ArrayData = newstring[2];
            ArrayData = strngData.Split(' ');
            strSchool = ArrayData[0];
            strStudent = ArrayData[1];
            RollNo = Convert.ToInt16(ArrayData[2]); 
        }
    }
}

Below is the image snapshot taken from Visual Studio

After solution is built then press "ctrl + F5" on keyboard and you will see output on console prompt where student's data is displayed as individual information through variable which is

School Name: St.GeorgeHighSchool

Student Name: Bannie

Roll No.: 20

Output shown the console prompt

Above code is working fine and it is also displaying result on console prompt. But the problem is with the way coding is done is not proper it is just written in random manner to produce output. In short we can say that code is not tidy enough, all variables are individuals which make things tedious and also code is lengthy due to which it lacks readability.

So how about making improvement one by one into the code where first we will move individual information of student into a logical object called student data which will reduce code writing extensively. Then later using this object or pass it wherever we wish to make use of the code and with this kind of approach code becomes more tidy and readable.

Argument

This can even be achieved by using classes. But by doing so it can lead to overdoing of things like classes, objects and properties etc. So in order to keep things simpler as our requirement is too small we will not make use of class and will use Tuples and learn about it. As here we do not require any "set" and "get" properties nor any type of validation so Tuple fits best for our current example scenario.

Getting Tuples into the picture

Tuples are objects which are used to logically group other kinds of objects so that it can be passed, used and accessed anywhere. Tuples does the grouping of multiple values into single result and useful when used returning function so that C# other parameters like "ref" & "out" can be avoided. It not only works with simple datatype like int, string, bool but also it works with object of arrays or you can even have custom objects etc and many more.

In our example we will create tuple called "StudentData" which will reduce individual variable of student's information. So following are the changes which needs to be done on Visual Studio.

  1. Starting with function remove void along with "out" datatype from code and create Tuple with three datatype <string, string, int>

  2. Create Tuple which forms logical object and it will return value through an array. For "int" datatype do conversion with code Convert.Int16.
  3.  = (ArrayData[0], ArrayData[1], Convert.ToInt16(ArrayData[2]))
  4. After Tuple is created now call it on Main method using a variable called "StudentData" and pass student information through it.
  5. Print first line which will have school name for that which is represented by "Item1" for School name. As we have sequenced it first while coding so write StudentData.Item1.
  6. Console.WriteLine("School Name:" + StudentData.Item1);
  7. Then print second line which will have student name for that which is represented by "Item2" for School name. Student name is sequenced it second while coding so write StudentData.Item2.
  8. Console.WriteLine("Student Name:" + StudentData.Item2);
  9. Finally print thirdline which will have roll number of student which is represented by "Item3". Roll number is sequenced it third while coding so write StudentData.Item3
  10. Console.WriteLine("Roll No.:" + StudentData.Item3);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
classProgram
    {
staticvoid Main(string[] args)
        {
string strng = "St.GeorgeHighSchool Bannie 20";

var StudentData = PData(strng);
Console.WriteLine("School Name:" + StudentData.Item1);
Console.WriteLine("Student Name:" + StudentData.Item2);
Console.WriteLine("Roll No.:" + StudentData.Item3);
Console.ReadLine();
        }

staticTuple PData(string strngData)
        {
string[] ArrayData = newstring[2];
            ArrayData = strngData.Split(' ');
returnTuple.Create(ArrayData[0], ArrayData[1], Convert.ToInt16(ArrayData[2]));

        }
    }
}

Now we achieved what we wanted from Tuple of reducing individual variable and getting clubbed same into one logical unit using Tuple. Our code has also improved a lot in terms of readability and tidiness.

But Tuples still have issues when it is called under Main method via a variable its attributes are Item1, Item2, Item 3 and so on. Its attributes can only be understood by its creator and if suppose tomorrow some other developer or some reader reads it cannot be recognized by them unless they know Item1 > School Name, Item 2 > Student Name and Item 3 > Roll Number.

So we can say Tuples made our code more tidy and readable from existing code. But still it is unreadable where it comes to attributes reading. In order to make attribute reading more meaningful and readable we will use anonymous type. In the next part of our article we will discuss and show practical use of anonymous type.

This article is written by one of QuestPond's fresher student taught during C# lectures. Below is one fine fresher video uploaded on YouTube from project based series: -

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Nov
22
2016

Anonymous Methods in C# with an example Step by Step

CLICK TO READ FULL ARTICLE

Views - 4435 |Category - C#

Oct
30
2014

Understand Monitor vs Mutex vs Semaphore vs SemaphoreSlim - Onlinebuff

CLICK TO READ FULL ARTICLE

Views - 21733 |Category - C#

Oct
18
2014

Thread Pooling in C#.NET with real time example - Onlinebuff

CLICK TO READ FULL ARTICLE

Views - 17588 |Category - C#

Oct
06
2014

Step by Step Partial Classes and Partial Methods in C#.NET with example

CLICK TO READ FULL ARTICLE

Views - 9576 |Category - C#

Sep
16
2014

Understand threading and types of threading in c# using an example

CLICK TO READ FULL ARTICLE

Views - 16109 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

l3g5g