Download - What's new in C# 6?
James MontemagnoDeveloper Evangelist, Xamarin@JamesMontemagno | motzcod.es
What’s new in C# 6?
Who’s this guy?
JamesMontemagnoDeveloper Evangelist, Xamarin
motzcod.es @JamesMontemagno
C# 6.0 => Clean up your codeJuly 2015
.NET 4.6VS 2015Xamarin Studio
• Auto-property Enhancements• Expression-Bodied Members• Null Propagator• String Interpolation• MORE!• Await in catch/finally• Exception Filters• nameof Operator• Dictionary Initializer• Import Static Type
C# 6.0 => Monkeys
public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; private set; } public string Name { get; set; } public string Location { get; set; }
public DayOfWeek MostActiveDay { get { return Id == 0 ? DayOfWeek.Friday : DayOfWeek.Monday; } } public void Print() { Console.WriteLine("We printed some stuff"); } public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
Auto properties
public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; private set; } public string Name { get; set; } public string Location { get; set; }
public DayOfWeek MostActiveDay { get { return Id == 0 ? DayOfWeek.Friday : DayOfWeek.Monday; } } public void Print() { Console.WriteLine("We printed some stuff"); } public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
Autoproperties
public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } public string Name { get; } public string Location { get; set; }
public DayOfWeek MostActiveDay { get { return Id == 0 ? DayOfWeek.Friday : DayOfWeek.Monday; } } public void Print() { Console.WriteLine("We printed some stuff"); } public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
Initializers
public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay { get { return Id == 0 ? DayOfWeek.Friday : DayOfWeek.Monday; } } public void Print() { Console.WriteLine("We printed some stuff"); } public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
Usingstatic
public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay { get { return Id == 0 ? DayOfWeek.Friday : DayOfWeek.Monday; } } public void Print() { Console.WriteLine("We printed some stuff"); } public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
Usingstatic
using static System.Console; using static System.DayOfWeek; public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay { get { return Id == 0 ? Friday : Monday; } } public void Print() { WriteLine("We printed some stuff"); } public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
Expression-bodiedfunctions!
using static System.Console; using static System.DayOfWeek; public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay { get { return Id == 0 ? Friday : Monday; } } public void Print() { WriteLine("We printed some stuff"); } public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
Expression-bodiedfunctions!
using static System.Console; using static System.DayOfWeek; public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay => Id == 0 ? Friday : Monday; public void Print() { WriteLine("We printed some stuff"); } public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
Expression-bodiedfunctions!
using static System.Console; using static System.DayOfWeek; public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay => Id == 0 ? Friday : Monday; public void Print() { WriteLine("We printed some stuff"); } public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
Expression-bodiedfunctions!
using static System.Console; using static System.DayOfWeek; public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay => Id == 0 ? Friday : Monday; public void Print() => WriteLine("We printed some stuff"); public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
StringInterpolation
using static System.Console; using static System.DayOfWeek; public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay => Id == 0 ? Friday : Monday; public void Print() => WriteLine("We printed some stuff"); public string DisplayName { get { return string.Format("Monkey {0} lives in {1} with Id of {2}", Name, Location, Id); } } }
StringInterpolation
using static System.Console; using static System.DayOfWeek; public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay => Id == 0 ? Friday : Monday; public void Print() => WriteLine("We printed some stuff"); public string DisplayName { get { return $"Monkey {Name} lives in {Location} with Id of {Id}"; } } }
StringInterpolation
using static System.Console; using static System.DayOfWeek; public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay => return Id == 0 ? Friday : Monday; public void Print() => WriteLine("We printed some stuff"); public string DisplayName { get { return $"Monkey {Name} lives in {Location} with Id of " + "{(Id == 0 ? \"Bananas\" : Id)}"; } } }
StringInterpolation
using static System.Console; using static System.DayOfWeek; public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay => Id == 0 ? Friday : Monday; public void Print() => WriteLine("We printed some stuff"); public string DisplayName => $"Monkey {Name} lives in {Location} with Id of " + "{(Id == 0 ? \"Bananas\" : Id)}"; }
C# 6.0 =>Monkeys
using static System.Console; using static System.DayOfWeek; public class Monkey { public Monkey() { } public Monkey(int id, string name, string location) { Id = id; Name = name; Location = location; }
public int Id { get; } = 0; public string Name { get; } = "Sofia"; public string Location { get; set; } = "South America";
public DayOfWeek MostActiveDay => Id == 0 ? Friday : Monday; public void Print() => WriteLine("We printed some stuff"); public string DisplayName => $"Monkey {Name} lives in {Location} with Id of " + "{(Id == 0 ? \"Bananas\" : Id)}"; }
?.
Null-Conditional Operatorsvar length = 0;if(customers != null) length = customers.Length;
int? length = customers?.Length; // null if customers is null
Customer first = nullif(length >0) first = customers[0];
Customer first = customers?[0]; // null if customers is null
int length = customers?.Length ?? 0;
If null then null, if not then dot
Clean up those events! public void OnPropertyChanged(string name) { var changed = PropertyChanged; if (changed == null) return;
changed(this, new PropertyChangedEventArgs(name)); }
Null checks… stink public void OnPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }
Some more cool stuff
Await in catch & finally blocksResource res = null; try { res = await Resource.OpenAsync(…); // You could do this. … } catch(ResourceException e) { await Resource.LogAsync(res, e); // Now you can do this … } finally { if (res != null) await res.CloseAsync(); // … and this. }
Exception FiltersResource res = null; try { res = await Resource.OpenAsync(…); // You could do this. … } catch(ResourceException e) when (e.Code == 0){ await Resource.LogAsync(res, e); // Now you can do this … } finally { if (res != null) await res.CloseAsync(); // … and this. }
Exception FiltersResource res = null; try { res = await Resource.OpenAsync(…); // You could do this. … } catch(ResourceException e) when (myFilter(e)){ await Resource.LogAsync(res, e); // Now you can do this … } finally { if (res != null) await res.CloseAsync(); // … and this. }
Exception Filtersprivate static bool Log(Exception e) { /* log it */ ; return false; }
… try { … } catch (Exception e) when (Log(e)) {}
Extension Methodsusing System.Linq; IEnumerable<int> range2 = Enumerable.Range(4, 3);IEnumerable<int> squares = range2.Select(x => x * x); foreach (int num in squares) { Console.WriteLine(num); }
/*This code produces the following output:162536*/
Extension Methodsusing static System.Console;using static System.Linq.Enumerable;
Extension Methodsusing static System.Console;using static System.Linq.Enumerable;
var range = Range(4, 3);//var squares = Select(range, x => x * x); //Not in scopevar squares2 = range.Select(x => x * x);
foreach (int num in squares2){ WriteLine(num);}
nameof expressionspublic static void GetMonkey(int count) { if(count < 0) throw new ArgumentNullException("count");
var monkeys = GetMonkeys(); WriteLine("Name: " + monkeys[0].Name); // prints "Name Sofia" }
nameof expressionspublic static void GetMonkey(int count) { if(count < 0) throw new ArgumentNullException(nameof(count));
var monkeys = GetMonkeys(); WriteLine(nameof(monkeys[0].Name) + ": " + monkeys[0].Name); // prints "Name Sofia" }
Index InitializersInsights.Report(exception, new Dictionary <string, string> { {"Some additional info", "foobar"}, {"Name", "James"} } );
Index InitializersInsights.Report(exception, new Dictionary <string, string> { ["Some additional info"] = "foobar", ["Name"] = "James" } );
Index Initializersvar numbers = new Dictionary<int, string> { [7] = "seven", [9] = "nine", [13] = "thirteen" };
Let’s C# 6!
• My Favorites• Tuples• Pattern Matching• Non-Nullable
What’s next? C# 7.0
Tuplespublic void Tally(IEnumerable<int> values, out int sum, out int count){ ... }
int s, c; Tally(myValues, out s, out c); Console.WriteLine($"Sum: {s}, count: {c}");
public Tuple<int, int> Tally(IEnumerable<int> values){ ... }
var t = Tally(myValues);Console.WriteLine($"Sum: {t.Item1}, count: {t.Item2}");
Tuples typespublic (int sum, int count) Tally(IEnumerable<int> values){ ... }
var t = Tally(myValues); Console.WriteLine($"Sum: {t.sum}, count: {t.count}");
public async Task<(int sum, int count)> TallyAsync(IEnumerable<int> values){ ... }
var t = await TallyAsync(myValues); Console.WriteLine($"Sum: {t.sum}, count: {t.count}");
Tuples literalsvar t = new (int sum, int count) { sum = 0, count = 0 }; // out of the box today syntax
public (int sum, int count) Tally(IEnumerable<int> values) { var s = 0; var c = 0; foreach (var value in values) { s += value; c++; } return (s, c); // target typed to (int sum, int count)}
public (int sum, int count) Tally(IEnumerable<int> values){ var res = (sum: 0, count: 0); // infer tuple type from //names and values foreach (var value in values) { res.sum += value; res.count++; } return res; }
Pattern Matchingvar v = expr as Monkey; if (v != null){ // code using v }
if (expr is Monkey v) { // code using v //v.Name}
int? x = 3;if (x is int v){ // code using v }
Pattern MatchingType? v = x?.y?.z;if (v.HasValue) { var value = v.GetValueOrDefault(); // code using value }
if (x?.y?.z is Type value){ // code using value }
Non-Nullablepublic class Dog { public string Name { get; private set; } public Dog(string name) { Name = name; } public void Bark() { } }
Dog! myMandatoryDog = new Dog("Mandatory"); Dog? myNullableDog = new Dog("Nullable"); Dog myGeneralDog = new Dog("General");
Dog! mandatoryDog = null; // Compiler Error.Dog? nullableDog = null; // OK.
• Strong Interest from C# Team• Tuples• Pattern Matching• Records / algebraic data types• Nullability Tracking• Async Streams/Disposal• Strongy Typed Access to Wire Formats
• So Much More:• Covariant return types, Expression trees, syntax for lists/dictionary,
immutable types, type providers
So Much More
http://bit.ly/csharp7-proposals
• C# 6 Features• http://bit.ly/csharp6-features
• C# 6 Overview by Mads Torgersen• https://channel9.msdn.com/Series/ConnectOn-Demand/211
• C# 7 Proposals• http://bit.ly/csharp7-proposals
Resources
Thank you.
JamesMontemagnoDeveloper Evangelist, Xamarin
motzcod.es @JamesMontemagno
Questions?