Python Style Tuple In C#
Contents
What Is Tuple In Python?
A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable.
Lets see some code example in python,
Similar code in C#
Lets see how C# went from close to actual python style tuple in C#,
Far From Python Style Tuple
The Tuple
Lets see some sample code
Tuples can be used in the following scenarios:
- When you want to return multiple values from a method without using ref or out parameters.
- When you want to pass multiple values to a method through a single parameter.
- When you want to hold a database record or some values temporarily without creating a separate class.
Tuple Limitations:
- Tuple is a reference type and not a value type. It allocates on heap and could result in CPU intensive operations.
- Tuple is limited to include 8 elements. You need to use nested tuples if you need to store more elements. However, this may result in ambiguity.
- Tuple elements can be accessed using properties with a name pattern Item
which does not make sense.
C# 7 includes ValueTuple to overcome the limitations of Tuple and also makes it even easier to work with Tuple. Lets learn more about it,
Python Style Tuple In C# 7.0
C# 7.0 (.NET Framework 4.7) introduced ValueTuple, a structure which is a value type representation of the Tuple.
The ValueTuple is only available in .NET Framework 4.7. If you don’t see ValueTuple in your project then you need to install the ValueTuple. (.NET Framework 4.7 or higher, or .NET Standard Library 2.0 or higher already includes ValueTuple.)
To install the ValueTuple package, right click on the project in the solution explorer and select Manage NuGet Packages… This will open the NuGet Package Manager. Click the Browse tab, search for ValueTuple in the search box and select the System.ValueTuple package.
Lets see some code example,
You may have notice now from above example how this C# tuples are now much alike to python style tuples. We can also specify different member names for a ValueTuple returned from a method.
ValueTuple also allows “discards” in deconstruction for the members you are not going to use.
You can learn more about ValueType Tuples in C# here.
References
Subscribe to Code with Shadman
Get the latest posts delivered right to your inbox