summaryrefslogtreecommitdiffhomepage
path: root/csharp.html.markdown
diff options
context:
space:
mode:
authorAndre Polykanine A.K.A. Menelion ElensĂșlĂ« <andre@oire.org>2017-10-27 02:18:07 +0300
committerGitHub <noreply@github.com>2017-10-27 02:18:07 +0300
commit41ffb9c42f633335df3e3109be1207a14ee4cfb7 (patch)
tree3aaa7b8a694dd1a2f1f019288d7edd5ae243e745 /csharp.html.markdown
parent4a40fa210a4e96946c2c80e469b44bc0252caad3 (diff)
parent4eb33f98b47dfbf6ae0c7c2148faadab310f53c5 (diff)
Merge pull request #2949 from ksami/ksami-csharp-tuples
[csharp/en] Add topics for tuples to csharp/en
Diffstat (limited to 'csharp.html.markdown')
-rw-r--r--csharp.html.markdown72
1 files changed, 56 insertions, 16 deletions
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 24ce803e..3790747c 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -1154,25 +1154,65 @@ namespace Learning.More.CSharp
}
}
+//New C# 7 Feature
+//Install Microsoft.Net.Compilers Latest from Nuget
+//Install System.ValueTuple Latest from Nuget
using System;
namespace Csharp7
{
- //New C# 7 Feature
- //Install Microsoft.Net.Compilers Latest from Nuget
- //Install System.ValueTuple Latest from Nuget
- class Program
- {
- static void Main(string[] args)
- {
- //Type 1 Declaration
- (string FirstName, string LastName) names1 = ("Peter", "Parker");
- Console.WriteLine(names1.FirstName);
-
- //Type 2 Declaration
- var names2 = (First:"Peter", Last:"Parker");
- Console.WriteLine(names2.Last);
- }
- }
+ // TUPLES, DECONSTRUCTION AND DISCARDS
+ class TuplesTest
+ {
+ public (string, string) GetName()
+ {
+ // Fields in tuples are by default named Item1, Item2...
+ var names1 = ("Peter", "Parker");
+ Console.WriteLine(names1.Item2); // => Parker
+
+ // Fields can instead be explicitly named
+ // Type 1 Declaration
+ (string FirstName, string LastName) names2 = ("Peter", "Parker");
+
+ // Type 2 Declaration
+ var names3 = (First:"Peter", Last:"Parker");
+
+ Console.WriteLine(names2.FirstName); // => Peter
+ Console.WriteLine(names3.Last); // => Parker
+
+ return names3;
+ }
+
+ public string GetLastName() {
+ var fullName = GetName();
+
+ // Tuples can be deconstructed
+ (string firstName, string lastName) = fullName;
+
+ // Fields in a deconstructed tuple can be discarded by using _
+ var (_, last) = fullName;
+ return last;
+ }
+
+ // Any type can be deconstructed in the same way by
+ // specifying a Deconstruct method
+ public int randomNumber = 4;
+ public int anotherRandomNumber = 10;
+
+ public void Deconstruct(out int randomNumber, out int anotherRandomNumber)
+ {
+ randomNumber = this.randomNumber;
+ anotherRandomNumber = this.anotherRandomNumber;
+ }
+
+ static void Main(string[] args)
+ {
+ var tt = new TuplesTest();
+ (int num1, int num2) = tt;
+ Console.WriteLine($"num1: {num1}, num2: {num2}"); // => num1: 4, num2: 10
+
+ Console.WriteLine(tt.GetLastName());
+ }
+ }
}
```