Get Started with Tuples in C#: A Beginner's Handbook | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (175).NET Core  (29).NET MAUI  (208)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (220)BoldSign  (15)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (67)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (101)Streamlit  (1)Succinctly series  (131)Syncfusion  (920)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (37)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (151)Chart  (132)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (633)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (41)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (508)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (11)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (597)What's new  (333)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Working with Tuple in C#

Get Started with Tuples in C#: A Beginner’s Handbook

We create tons of classes to create objects for many scenarios during software development. But sometimes, we don’t need to create a new class for an object with few properties. To handle these cases, C# offers a feature named tuples.

This article will discuss tuples in C# with some practical use cases for better understanding.

What is a tuple in C#?

As developers, we have used many data structures, such as arrays, queues, and linked lists, to categorize and handle data. A tuple is a simple and lightweight data structure consisting of multiple elements to represent data. It is available in C# 7.0 and higher versions.

Tuples help us access and manipulate data sets easily for different operations without having to define a new class with custom properties. First, let’s explore tuples with some examples.

Easily build cross-platform mobile and desktop apps with the flexible and feature-rich controls of the Syncfusion .NET MAUI platform.

Basic example for a tuple in C#

Here, we’ll show how to create a tuple with a basic example in C#.

(int, string) employee1 = (23, "Yohan");
Console.WriteLine($"{employee1.Item2} is {employee1.Item1} years old");
//Yohan is 23 years old

In this example, the requirement is to create a simple employee object to access an employee’s name and age. For this case, creating a tuple would be enough, rather than creating a class. We have created properties of type int and string in this tuple. When you haven’t provided names to the properties, you can access the properties using the syntax employee1.item1.

Tuples with fields names in C#

We didn’t use field names in the previous example. But we can provide names to the properties. Refer to the following code example.

(int Age, string Name) employee1 = (23, "Yohan");
Console.WriteLine($"{employee1.Name} is {employee1.Age} years old"); 
//Yohan is 23 years old

We used field names for the data in the employee1 tuple. Then, we could access the data using field names. The code is more readable when using the field names.

Nested tuple in C#

You can also create multiple tuples inside one tuple as nested tuples. To create nested tuples, refer to the following example.

var employees = ((23, "Yohan"), (45, "Jhon Doe"), (34, "Jon Jones"));

We have declared a nested tuple with three tuples that use int and string properties. We can now access these items one by one as needed.

To access the first nested tuple in the employee tuple, see the following code.

Console.WriteLine(employees.Item1); 
//(23, "Yohan")

We can also access the item inside the nested tuple.

Console.WriteLine(employees.Item1.item1); 
//23

Every property of the Syncfusion .NET MAUI controls is completely documented to make it easy to get started.

Tuple as a function parameter in C#

We can also use tuples as parameters for functions. Let’s create a function using a tuple as a parameter, as in the following code.

public void GetEmployee((string Name, int Age) employee)
{
    Console.WriteLine($"{employee.Name} is {employee.Age} years old");
}

Then, call this function inside the Main method, as in the following code example.

public class TupleDemo
{
    public void GetEmployee((string Name, int Age) employee)
    {
        Console.WriteLine($"{employee.Name} is {employee.Age} years old");
    }
    public static void Main(string[] args)
    {
        var tupleDemo = new TupleDemo();
        tupleDemo.GetEmployee(("Yohan", 23));
    }
}
//Yohan is 23 years old

In this code, we created the class object for TupleDemo and then called the GetEmployee function using that object. Also, we passed a tuple as the parameter for this function. In this case, we have created the tuple as the parameter for the GetEmployee method.

Tuple as the return type in C#

We can use a tuple as the return type for functions. But for that, we have to use tuple for the return type, as in the following function.

public (string, int) GetEmployee()
{
    return ("Yohan", 23);
}

In it, we created the function named GetEmployee with a tuple as the return type. Here, we have returned the tuple, which contains string and int data properties.

Refer to the following code to call the function GetEmployee and access the values of the tuple.

public class TupleDemo
{
    public static void Main(string[] args)
    {
        var tupleDemo = new TupleDemo();
        var employee = tupleDemo.GetEmployee();
        Console.WriteLine($"{employee.Item1} is {employee.Item2} years old");
    }
    
    public (string, int) GetEmployee()
    {
        return ("Yohan", 23);
    }
}
//Yohan is 23 years old

To make it easy for developers to include Syncfusion .NET MAUI controls in their projects, we have shared some working ones.

Tuple deconstruction in C#

Let’s look at this example.

public class TupleDemo
{
    public static void Main(string[] args)
    {
        var tupleDemo = new TupleDemo();
        var employee = tupleDemo.GetEmployee();
        Console.WriteLine($"{employee.Item1} is {employee.Item2} years old");
    }
    
    public (string, int) GetEmployee()
    {
        return ("Yohan", 23);
    }
}
//Yohan is 23 years old

In this example, we created the function named GetEmployee with tuple as the return type. Then, we called that function by creating the class object and accessing the data of the tuple. We have access to the data like this employee.Item1. But, it is less readable. We can use tuple deconstruction to rescue it.

public class TupleDemo
{
    public void GetEmployee((string Name, int Age) employee)
    {
        Console.WriteLine($"{employee.Name} is {employee.Age} years old");
    }
    public static void Main(string[] args)
    {
        var tupleDemo = new TupleDemo();
        (string Name, int Age) = tupleDemo.GetEmployee();
        Console.WriteLine($"{Name} is {Age} years old");
    }
    
    public (string, int) GetEmployee()
    {
        return ("Yohan", 23);
    }
}
//Yohan is 23 years old

In this example, we have used tuple deconstruction to unpackage all items in a tuple with a single-line operation.

(string Name, int Age) = tupleDemo.GetEmployee();

We can increase the readability of the code by using tuple deconstruction when using tuples.

Conclusion

This article demonstrated the usage of tuples in C# programming with some useful scenarios and code examples.

The tuple is a good programming concept that will help to reduce the need to create classes and structs when we don’t need them. We can also use them to pass multiple values to the functions and use them as the return type.

I hope this article was helpful in learning about tuples in C#.

Thank you for reading!

Syncfusion’s Essential Studio is a software package that provides state-of-the-art solutions for startups and enterprises. It includes more than 1,700 components and frameworks for WinForms, WPF, .NET MAUI, ASP.NET (Web Forms, MVC, Core), UWP, WinUI, Xamarin, Flutter, Blazor, JavaScript, Angular, Vue, and React that make developers’ work easier.

Please share your feedback as comments on this blog. You can also reach us through our support forums, support portal, or feedback portal.

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed