Created
March 19, 2017 04:03
-
-
Save mstum/796653cfa4a3ebeb5d3303457efde49c to your computer and use it in GitHub Desktop.
C# 7 Features
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace CSharp7Features | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
OutVariables(); | |
PatternMatching("123"); | |
BetterSwitchCase("123"); | |
BetterSwitchCase("Foo"); | |
// ValueTuple NuGet Package Required: | |
// Install-Package "System.ValueTuple" | |
var tuplesYay = TuplesYay(); | |
Console.WriteLine($"Tuples Result: {tuplesYay.result}, Error: {tuplesYay.error}"); | |
LocalFunction(); | |
Console.ReadLine(); | |
} | |
private static void OutVariables() | |
{ | |
string s = "123"; | |
if (int.TryParse(s, out var i)) | |
{ | |
Console.WriteLine($"s is the integer {i}."); | |
} | |
} | |
private static void PatternMatching(object obj) | |
{ | |
if(obj is string s && int.TryParse(s, out var i)) | |
{ | |
Console.WriteLine($"Input Variable was a string ({s}), and parsed to the int {i}."); | |
} | |
} | |
private static void BetterSwitchCase(string s) | |
{ | |
switch (s) | |
{ | |
case string x when x.Length == 3 && int.TryParse(x, out int i): | |
Console.WriteLine($"s is a string that parses to {i}"); | |
break; | |
default: | |
Console.WriteLine("No Match."); | |
break; | |
} | |
} | |
// ValueTuple NuGet Package Required: | |
// Install-Package "System.ValueTuple" | |
private static (bool result, string error) TuplesYay() | |
{ | |
return (true, "Foo"); | |
} | |
private static void LocalFunction() | |
{ | |
// Instead of having to declare a Func<> or Action<>. Can even call itself! | |
void Log(string message) { | |
Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {message}"); | |
} | |
(int current, int previous) Fib(int i) | |
{ | |
if (i == 0) | |
{ | |
Log("Fib of 0: 1"); | |
return (1, 0); | |
} | |
var (p, pp) = Fib(i - 1); | |
var tmpResult = (p + pp, p); | |
Log($"Fib of {i}: {tmpResult.Item1}"); | |
return tmpResult; | |
} | |
(int result, int previous) = Fib(5); | |
Log("Final Result: " + result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment