Friday, August 30, 2019

C# Tutorial - Tuple Type

C# Tuple type was introduced in .Net Framework 4.0 and a tuple is a data structure that contains a sequence of elements of different data types.
Basically it is very useful to return the multiple values from method without creating new type.


Creation of Tuple object:

Here is an example of Tuple type, which is holding employee information like employee ID, First Name and Last Name

Tuple<int, string, string> employee = new Tuple<int, string, string>(1, "Steve", "Bobs");

We can create an instance of the tuple by calling Create(T1,) method of static class Tuple.

Tuple<int, string, string> employee = Tuple.Create(1, "Steve", "Bobs");

tuple object stores data as collection of Item properties like Item1, Item2, Item3, Item4, Item5, Item6, Item7 and Rest, so max tuple can stores only 8 item in one dimension and if you want to store more elements, you need to use nested tuples

Here is an example of nested tuple,  how to store the employee information including address by using nested Tuple:

var emp = new Tuple<int, string, string, Tuple<string, string, string, string, string>>(1, "Steve", "Jobs", new Tuple<string, string, string, string, string>("Street Address","City","State","County","ZipCode"));

Access of Tuple Element:

The element of a tuple can be accessed by using element property like Item1, Item2.

Here is an example how to access the tuple data.

Tuple<int, string, string> employee = Tuple.Create(1, "Steve", " Bobs");

int employeeID = employee.Item1;
string firstName = employee.Item2;
string lastName = employee.Item3;


Tuple in a method:

A Tuple type can be used as a method parameter or return type of a method.

Here is an example of a method returns multiple value as a tuple type

public Tuple<int, string, string> GetEmployeeTuple(int employeeID, string FirstName, string LastName )
{
   Tuple<int, string, string> employee = Tuple.Create(employeeID, FirstName, LastName);
   return employee;
}


No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...