TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# ValueTuple Examples (System.ValueTuple, ToTuple)

Use the ValueTuple type from System.ValueTuple. Call the ToTuple method.
ValueTuple. Consider the Tuple class: its syntax is hard to type and remember. We must specify its items' types. What if we could remove this complexity for clearer programs?Tuple
And what if we could optimize tuples to avoid allocations? With ValueTuple, from the package System.ValueTuple, we can use optimized tuples.
System.ValueTuple. With a ValueTuple, we can use a simpler syntax form to create and handle tuples. Add the System.ValueTuple package to your program (it is a NuGet package).

Here: We create a 3-item ValueTuple. It is the same as a Tuple of the specified items, except it has simpler syntax and a ToTuple method.

C# program that uses System.ValueTuple using System; class Program { static void Main() { // Make sure System.ValueTuple is referenced in the project. // ... Create 3-item ValueTuple. var data = (10, "bird", 1.5); // Test an item. if (data.Item1 == 10) { Console.WriteLine(data); } } } Output (10, bird, 1.5)
ToTuple. Here we use the ToTuple method on the ValueTuple. Make sure you add the System.ValueTuple package. We can convert a ValueTuple to a Tuple.
C# program that uses ValueTuple, ToTuple using System; class Program { static void Main() { // Create a ValueTuple. var unit = (10, 20, 'X'); // Convert to a Tuple. Tuple<int, int, char> tuple = unit.ToTuple(); Console.WriteLine(unit.GetType()); Console.WriteLine(unit); Console.WriteLine(tuple.GetType()); Console.WriteLine(tuple); } } Output System.ValueTuple`3[System.Int32,System.Int32,System.Char] (10, 20, X) System.Tuple`3[System.Int32,System.Int32,System.Char] (10, 20, X)
ValueTuple, names. With the ValueTuple syntax we can improve the readability of code that uses tuples. We do not need to use Item1, Item2 syntax—we can access items by a label or name.
C# program that uses ValueTuple, names using System; class Program { static void Main() { // Create a ValueTuple with names. var result = (count: 10, animal: "scorpion"); // Access items by their names. Console.WriteLine(result.count); Console.WriteLine(result.animal); } } Output 10 scorpion
ValueTuple, deconstruction. With a ValueTuple, we can "deconstruct" a return value from a method. Consider this example. CatInfo returns a 2-item ValueTuple.

And: We then deconstruct the returned tuple in the Main method. We can access the cat's size and name directly.

C# program that uses ValueTuple, deconstruction using System; class Program { static (int, string) CatInfo() { // Return a ValueTuple with an int and string. return (10, "Mittens"); } static void Main() { // deconstructthe[ValueTuple] var (size, name) = CatInfo(); // Display the values. Console.WriteLine($"Cat size = {size}; name = {name}"); } } Output Cat size = 10; name = Mittens
ValueTuple, type error. To use a ValueTuple, you may need to add a package from NuGet in Visual Studio. In Visual Studio, use "Manage NuGet Packages" and search for "ValueType."
C# program that causes predefined type error class Program { static void Main() { // Make sure System.ValueTuple is imported. var unit = ("bird", "blue", 5); } } Output Error CS8179 Predefined type 'System.ValueTuple`3' is not defined or imported
Benchmark, ValueTuple. With a Tuple, we must allocate a class instance. But with ValueTuple, the Framework uses dynamic types to reduce overhead. Let's test this.

Here: Method1 and Method2 both return a 2-item result. Method1 uses Tuple, and Method2 use a value tuple.

Result: The new ValueTuple is faster. With ValueTuple we have both simpler syntax and improved performance.

C# program that benchmarks Tuple, ValueTuple using System; using System.Diagnostics; class Program { static Tuple<int, string> Method1() { return new Tuple<int, string>(10, "bird"); } static (int, string) Method2() { return (10, "bird"); } static void Main() { const int _max = 1000000; // Version 1: use Tuple class. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { var result = Method1(); if (result.Item1 != 10) { return; } } s1.Stop(); // Version 2: use ValueTuple. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { var result = Method2(); if (result.Item1 != 10) { return; } } s2.Stop(); Console.WriteLine(s1.Elapsed.TotalMilliseconds); Console.WriteLine(s2.Elapsed.TotalMilliseconds); } } Output 4.8384 Return Tuple 0.2571 Return ValueTuple
A summary. The standard Tuple class is still a useful class. But ValueTuple has advantages that are clear. It can be used to optimize return statements from methods.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf