क्रिश्चियन शॉ
  • होम
  • Blog
    • प्रोग्रामिंग
      • C#
      • पॉवरशेल
      • Python
      • SQL
    • वर्डप्रेस
      • ट्युटोरियल
    • क्लाउड
    • होम ऑटोमेशन
      • होम असिस्टेंट
        • Node-Red
    • Career
  • सेवाएं
  • शब्दकोष
  • About
No Result
View All Result
क्रिश्चियन शॉ
  • होम
  • Blog
    • प्रोग्रामिंग
      • C#
      • पॉवरशेल
      • Python
      • SQL
    • वर्डप्रेस
      • ट्युटोरियल
    • क्लाउड
    • होम ऑटोमेशन
      • होम असिस्टेंट
        • Node-Red
    • Career
  • सेवाएं
  • शब्दकोष
  • About
No Result
View All Result
क्रिश्चियन शॉ
No Result
View All Result
Home प्रोग्रामिंग C#
tuple, c# tuple, tuples

C# Tuple – How to use Tuples in C#

by ईसाई
2022-6-जुलाई
in C#
0

A tuple is a lightweight data structure that provides concise syntax to group multiple data elements. In this article, I will show you how to work with a C# tuple.

Ever been in need to pass multiple values around at the same time? By using a C# Tuple we can do just that – but with a little warning. Tuples can be hard to understand and use. When I first started using Tuples I asked myself: how are the values inside a tuple related? How can we place our data in a tuple into variables in the code that has meaningful names?

If you like me, create software and need a quick way to move data around, this guide will help you to do that by teaching you how to add tuples to your own project the right way.

If you are ready to get started with C# tuples and learn to get them working under the hood of your application, then let’s move on.

विषय-सूची
  1. Is C# Tuple the same as System.Tuple?
  2. When to use a Tuple?
  3. What is a Tuple in C#?
  4. Using System.Tuple
    • Type arguments with System.Tuple
    • Tuple.Create() – Why not just use new?
    • How to access data in System.Tuple?
    • How to update the value of a System.Tuple member?
  5. Using C# Tuple (System.ValueTuple) – Since C# 7
    • How to declare a C# Tuple?
    • How to update a C# tuple value?
    • How to use Named Tuples
    • How to do tuple deconstruction?
  6. Tuple vs Enum and Dictionary
  7. Summary

Is C# Tuple the same as System.Tuple?

When I started using tuples, I got confused by the two. A C# tuple is not the same as System.Tuple. System.Tuple makes use of a class and a C# tuple is backed by System.ValueTuple.

As I just mention, System.Tuple are classes, where System.ValueTuple are structs. The great thing about using a ValueTuple is that it is mutable and not “read-only” like a System.Tuple is. The members of System.ValueTuple are fields, where System.Tuple are properties (because of the class).

If you are using C# 7 or later, I would recommend you to use System.ValueTuple. If you are using an older version, then you are forced to use System.Tuple. I will show you how to use both of them in this article – don’t worry.

When to use a Tuple?

A tuple is perfect for moving data around in your application, without having to create a new model/class to hold your data.
The most common cases where I use tuples are:
– When I need to group related values.
– When I have to return multiple values from a function without using the out parameter.
– When I do LINQ projection. (When I need to extract a subset of elements from a sequence of data).

What is a Tuple in C#?

Tuple initially appeared in .NET framework 4.0 and it can contain up to seven elements plus one optional TRest property as the eighth element – (Tuple<T1,T2,T3,T4,T5,T6,T7,TRest>). The TRest property is mostly for extension purposes and can hold a nested tuple object.

Tuple should not be mistaken for ValueTuple, which has been introduced as an improvement in C#7. We’re going to talk about the differences a bit later on.

Using System.Tuple

System.Tuple is a tuple implementation that makes use of classes. This was the defacto standard prior to C# 7 – which is the reason why it’s widely used in many “old” applications. Lots of developers still use it.

Type arguments with System.Tuple

The old tuple classes require type arguments. When you create new tuples you must provide them using the new constructor. The number and types of tuple members are determined på the type arguments, hence they are important.

Below is an example of a tuple with two members of string type:

Tuple<string, string> names = new Tuple<string, string>("Christian", "Schou");

If you create a new tuple without specifying the type of arguments in the constructor, your compiler will return an error. Here is an example:

Tuple<string, string> names = new Tuple("Christian", "Schou");

Compilation error: Cannot create an instance of the static class 'System.Tuple'

Tuple.Create() – Why not just use new?

When working with System.Tuple, we got two options for creating tuples. Tuple.Create() and new Tuple(). So what is the difference? There is no difference… I prefer to use Tuple.Create() because I find it more concise and it makes my code easier to read for other developers including myself in the future when I have to come back and refactor something.

var names = Tuple.Create("Christian", "Schou"); // How I normally do it - easier to write

var names = new Tuple<string, string>("Christian", "Schou"); // Less concise

The core difference between the two is that you don’t have to specify your argument types when using Tuple.Create(). As I mentioned earlier, you will get a compiler error, if you don’t specify the argument types when using the new constructor.

If you take a look at the code behind it, you will see that both ways actually do the same thing. When you use Tuple.Create() it will call the Tuple() constructor with a set of default values.

Below is an example of how the two of them are doing the same job using generic arguments.

public static class Tuple
{
    public static Tuple<T1, T2, etc...> Create<T1, T2, etc...>(T1 item1, T2 item2, etc...) {
        return new Tuple<T1, T2, etc...>(item1, item2, etc...);
    }
}

How to access data in System.Tuple?

When you create a new tuple and want to access the data inside it (your values) you only have to specify the item you would like the value for. Elements in System.Tuple does not make use of names, instead, you have to use an ordinal index to access the values in your tuple.

var address = Tuple.Create("H.C. Andersen Haven 1", "Odense C", 5000, "Denmark");

string street = address.Item1; // H.C. Andersen Haven 1
string city = address.Item2 // Odense C
int zip = address.Item3 // 5000
string country = address.Item4 // Denmark

How to update the value of a System.Tuple member?

It’s easy – you cant. System.Tuple is immutable. Once it’s created, you cannot change it. If you try to do it, you will end up with a compiler error.

var carPrice = Tuple.Create("Mercedes EQE", 96726.60);

carPrice.Item2 = 88876.99; 

// Compilation error: Property or indexer 'Tuple<string, double>.Item2' cannot be assigned to -- it is read only

If you need to update the value, you would have to destroy and re-create the tuple with the new value you would like to have in the tuple:

var carPrice = Tuple.Create("Mercedes EQE", 96726.60);

Tuple.Create(carPrice.Item1, 88876.99);

Using C# Tuple (System.ValueTuple) – Since C# 7

Tuple in C# is a reference-type data structure that allows the storage of items of different data types. It comes in handy when we need to create an object that can hold items of different data types but we don’t want to create a completely new type.

My favorite and the one I always use if possible. The C# Tuple is a comma-separated list of values enclosed in parentheses. With this type, we can have nested tuples + values counting from 0 to many.

A C# tuple since C# 7 has the following syntax.

(double, int) t1 = (4.5, 3);
Console.WriteLine($"Tuple with elements {t1.Item1} and {t1.Item2}.");
// Output:
// Tuple with elements 4.5 and 3.

(double Sum, int Count) t2 = (4.5, 3);
Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");
// Output:
// Sum of 3 elements is 4.5.

How to declare a C# Tuple?

I always use names when specifying my tuples, to make the code easier to read and maintain. The ultimate easier method is just by using the parentheses syntax though.

In the example above you can see both ways to declare the tuples.

How to update a C# tuple value?

Opposite of System.Tuple, a C# tuple is mutable. The developers behind C# changed the new kind of tuples to be implemented as a ValueTuple which is a struct, that we are able to update.

It is very easy to update a tuple at runtime. We only have to specify the new value for the element in the tuple. An example is shown below of how you can accomplish that task.

var latLong = (55.39594, 10.38831); // Odense coordinates

latLong.Item1 = 55.05982;
latLong.Item2 = 10.60677;

Console.WriteLine(latLong); // (55.05982, 10.60677) - Svendborg coordinates

How to use Named Tuples

By default, each member of your tuple is constructed with a name like “item1”, “item2”, “item3”, etc… Whenever I see someone do that in C# 7 or later, I decline the pull request with a comment telling them to update the tuple with the naming of the members because it is harder to read the code for other developers resulting in a codebase that’s harder to maintain in the future. PLEASE use named tuples whenever possible!

Since C# 7 a new type of tuple has been introduced – “named tuple”. A named tuple can have named members – which makes the code easier to write and maintain.

Below is an example of how to create a named tuple based on the example above with coordinates.

(double latitude, double longitude) coordinates = (55.39594, 10.38831);

Console.WriteLine(coordinates); // (55.39594, 10.38831)

Console.WriteLine(coordinates.latitude); // 55.39594

Console.WriteLine(coordinates.longitude); // 10.38831

How to do tuple deconstruction?

Ever wondered how you could extract the value of a named tuple by creating a method? Tuple deconstruction is a nice feature that allows us to extract values from a tuple into separate variables.

C# got a special syntax we can use to deconstruct a C# tuple to get the value of the members. To deconstruct a C# tuple, you actually just have to use the same syntax as when you initially created the C# tuple.

Below is an example of how you can extract the city name from a tuple, with this format: (string, string, int, string). The only thing you have to do is call the method GetCity and pass the tuple to it:

public static string GetCity((string, string, int, string) cityName)
{
  (_, string, _, _) = cityName; 

  return cityName;
}

var address = ("H.C. Andersen Haven 1", "Odense C", 5000, "Denmark");

Console.WriteLine(GetCity(city)); // Odense C

The underscore(s) “_” is present because we would like to ignore the other values. We only want value number two (index 1) – the city from the C# tuple.

Tuple vs Enum and Dictionary

A tuple is very often used instead of an enum since enums in C# don’t support string values. I have made an example below to show you what I mean:

public enum StatusCodes
{
  New = "A new order has been received",
  Shipped = "The order has been shipped from the warehouse",
  Delivered = "The order has been delivered to the customer"
}

If we told our compiler to build this you would get a compiler error. The reason is that enums only support numeric values, hence tuples are a good idea to use. This would be a solution:

List<(string ShortStatus, string LongStatus)> statusCodes = new List<(string ShortStatus, string LongStatus)>() 
{ 
  ("New", "A new order has been received"), 
  ("Shipped", "The order has been shipped from the warehouse"),
  ("Delivered", "The order has been delivered to the customer")
};

Console.WriteLine(statusCodes[0].LongStatus); // A new order has been received

If you normally would you a dictionary, I would advise you to switch to C# tuples as they often are more concise.

You might be thinking – are they not quite the same? In some way. A dictionary like this: Dictionary<TKey, TValue> is a way to structure data into key-value pairs. You are able to store any type and any value you would like. The only problem is that you can only store one value per key. If you were using tuples, you would be able to store multiple values using the same key.

That’s why I often use a C# tuple instead of a dictionary.

Summary

In this article, we have taken a look at both types of tuples in the .NET ecosystem. A c# tuple is a great way to parse and return multiple values to/from a method without having to create a new model. Tuples can be difficult to understand, so please use them with caution.

Tuples should not be used in all cases. I got a rule of thumb that goes like this: If I got less than three items I will use a tuple to move data around. If you got more items, please create a class as they are easier to maintain and add a standard for that specific type of data.

I hope you learned some new programming techniques from this article. If you got any issues, questions or suggestions, please let me know in the comments. Happy coding!

Tags: .NET 5.0.NET 6.Net CoreASP.NET CoreC#DevelopmentTupleWeb
Previous Post

How to implement CQRS using MediatR in an ASP.NET Core Web API (.NET 6)

Next Post

How to do pattern matching in switch statements – C# version >= 7.0

ईसाई

ईसाई

Hello 👋 My name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Related Posts

watchdog
ASP.NET Core

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

by ईसाई
2022-13-अगस्त
0

A reader recently asked me for a more modern way to view log files for requests and exceptions in a...

Read more
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

2022-25-जुलाई
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

2022-23-जुलाई
Dockerize ASP.NET Core

How to Compose an ASP.NET Core Web API (.NET 6) with an MS SQL Server 2022 on Linux in Docker

2022-19-जुलाई
pattern matching in switch

How to do pattern matching in switch statements – C# version >= 7.0

2022-11-जुलाई
Next Post
pattern matching in switch

How to do pattern matching in switch statements - C# version >= 7.0

प्रातिक्रिया दे जवाब रद्द करें

आपका ईमेल पता प्रकाशित नहीं किया जाएगा. आवश्यक फ़ील्ड चिह्नित हैं *

क्रिश्चियन शॉ

क्रिश्चियन शॉ

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website
Career

Top 6 things to add on your personal website to get hired for a tech job

by ईसाई
2022-7-अगस्त
0

Back in the days before the internet was a thing like it is today, we used to have business cards...

Read more
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

2022-13-अगस्त
get hired for a tech job

5 tips to help you get hired for a tech job

2022-31-जुलाई
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

2022-25-जुलाई
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

2022-23-जुलाई

क्रिश्चियन शॉ

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website

Top 6 things to add on your personal website to get hired for a tech job

2022-7-अगस्त
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

2022-13-अगस्त
get hired for a tech job

5 tips to help you get hired for a tech job

2022-31-जुलाई
  • hi_INहिन्दी
    • da_DKDansk
    • en_USEnglish
    • de_DEDeutsch
    • pt_BRPortuguês do Brasil
  • Contact
  • गोपनीयता नीति
  • सेवा की शर्तें

© 2022 क्रिश्चियन शॉ - All rights reserved.

No Result
View All Result
  • होम
  • Blog
    • प्रोग्रामिंग
      • C#
      • पॉवरशेल
      • Python
      • SQL
    • वर्डप्रेस
      • ट्युटोरियल
    • क्लाउड
    • होम ऑटोमेशन
      • होम असिस्टेंट
    • Career
  • सेवाएं
  • शब्दकोष
  • About

© 2022 क्रिश्चियन शॉ - All rights reserved.

मैं आपकी वरीयताओं को याद करके और बार-बार आने वाली यात्राओं को याद करके आपको सबसे अधिक प्रासंगिक अनुभव देने के लिए अपनी वेबसाइट पर कुकीज़ का उपयोग करता हूं। “स्वीकार करें” पर क्लिक करके, आप सभी कुकीज़ के उपयोग के लिए सहमति देते हैं।
मेरी निजी जानकारी न बेचें.
कुकी सेटिंगACCEPT
गोपनीयता और कुकीज़ नीति

गोपनीयता अवलोकन

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
CookieDurationDescription
__gads1 year 24 daysThe __gads cookie, set by Google, is stored under DoubleClick domain and tracks the number of times users see an advert, measures the success of the campaign and calculates its revenue. This cookie can only be read from the domain they are set on and will not track any data while browsing through other sites.
_ga2 yearsThe _ga cookie, installed by Google Analytics, calculates visitor, session and campaign data and also keeps track of site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognize unique visitors.
_ga_0J2F6JVWSD2 yearsThis cookie is installed by Google Analytics.
_gat_gtag_UA_84232734_11 minuteSet by Google to distinguish users.
_gid1 dayInstalled by Google Analytics, _gid cookie stores information on how visitors use a website, while also creating an analytics report of the website's performance. Some of the data that are collected include the number of visitors, their source, and the pages they visit anonymously.
YouTube2 yearsYouTube sets this cookie via embedded youtube-videos and registers anonymous statistical data. I embed YouTube videos in my articles/tutorials - you won't get the full experience of the articles if this is deactivated.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
CookieDurationDescription
IDE1 year 24 daysGoogle DoubleClick IDE cookies are used to store information about how the user uses the website to present them with relevant ads and according to the user profile.
test_cookie15 minutesThe test_cookie is set by doubleclick.net and is used to determine if the user's browser supports cookies.
VISITOR_INFO1_LIVE5 months 27 daysA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.
YSCsessionYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.
yt-remote-connected-devicesneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
yt-remote-device-idneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Powered by CookieYes Logo