what's new in c# 6?

46
James Montemagno Developer Evangelist, Xamarin @JamesMontemagno | motzcod.es What’s new in C# 6?

Upload: james-montemagno

Post on 13-Jan-2017

534 views

Category:

Engineering


0 download

TRANSCRIPT

Page 1: What's new in C# 6?

James MontemagnoDeveloper Evangelist, Xamarin@JamesMontemagno | motzcod.es

What’s new in C# 6?

Page 2: What's new in C# 6?

Who’s this guy?

JamesMontemagnoDeveloper Evangelist, Xamarin

[email protected]

motzcod.es @JamesMontemagno

Page 3: What's new in C# 6?

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

Page 4: What's new in C# 6?

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);            }        }    }

Page 5: What's new in C# 6?

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);            }        }    }

Page 6: What's new in C# 6?

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);            }        }    }

Page 7: What's new in C# 6?

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);            }        }    }

Page 8: What's new in C# 6?

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);            }        }    }

Page 9: What's new in C# 6?

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);            }        }    }

Page 10: What's new in C# 6?

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);            }        }    }

Page 11: What's new in C# 6?

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);            }        }    }

Page 12: What's new in C# 6?

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);            }        }    }

Page 13: What's new in C# 6?

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);            }        }    }

Page 14: What's new in C# 6?

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);            }        }    }

Page 15: What's new in C# 6?

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}";             }        }    }

Page 16: What's new in C# 6?

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)}";             }        }    }

Page 17: What's new in C# 6?

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)}";     }

Page 18: What's new in C# 6?

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)}";     }

Page 19: What's new in C# 6?

?.

Page 20: What's new in C# 6?

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

Page 21: What's new in C# 6?

Clean up those events!  public void OnPropertyChanged(string name)        {            var changed = PropertyChanged;            if (changed == null)                return;

            changed(this, new PropertyChangedEventArgs(name));        }

Page 22: What's new in C# 6?

Null checks… stink  public void OnPropertyChanged(string name)        {            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));        }

Page 23: What's new in C# 6?

Some more cool stuff

Page 24: What's new in C# 6?

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. }

Page 25: What's new in C# 6?

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. }

Page 26: What's new in C# 6?

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. }

Page 27: What's new in C# 6?

Exception Filtersprivate static bool Log(Exception e) { /* log it */ ; return false; }

… try { … } catch (Exception e) when (Log(e)) {}

Page 28: What's new in C# 6?

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*/

Page 29: What's new in C# 6?

Extension Methodsusing static System.Console;using static System.Linq.Enumerable;

Page 30: What's new in C# 6?

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);}

Page 31: What's new in C# 6?

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"  }

Page 32: What's new in C# 6?

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"  }

Page 33: What's new in C# 6?

Index InitializersInsights.Report(exception,                 new Dictionary <string, string>                 {                     {"Some additional info", "foobar"},                    {"Name", "James"}                }            );

Page 34: What's new in C# 6?

Index InitializersInsights.Report(exception,                 new Dictionary <string, string>                 {                     ["Some additional info"] = "foobar",                    ["Name"] = "James"                }            );

Page 35: What's new in C# 6?

Index Initializersvar numbers = new Dictionary<int, string> {                            [7] = "seven",                            [9] = "nine",                            [13] = "thirteen"                        };

Page 36: What's new in C# 6?

Let’s C# 6!

Page 37: What's new in C# 6?

• My Favorites• Tuples• Pattern Matching• Non-Nullable

What’s next? C# 7.0

Page 38: What's new in C# 6?

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}");

Page 39: What's new in C# 6?

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}");

Page 40: What's new in C# 6?

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; }

Page 41: What's new in C# 6?

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 }

Page 42: What's new in C# 6?

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 }

Page 43: What's new in C# 6?

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.

Page 44: What's new in C# 6?

• 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

Page 45: What's new in C# 6?

• 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

Page 46: What's new in C# 6?

Thank you.

JamesMontemagnoDeveloper Evangelist, Xamarin

[email protected]

motzcod.es @JamesMontemagno

Questions?