Date post: | 08-Feb-2017 |
Category: |
Technology |
Upload: | abhishek-sur |
View: | 266 times |
Download: | 0 times |
C# 7.0What?! C# is Being Updated?
Abhishek Sur, Microsoft MVPArchitect, Insync
2
Page
History of C#
Page
3
C# 2.0
• Generics• Partial types• Anonymous methods• Iterators• Nullable types• Getter/Setter separate accessibility• Static classes• And more..
Page
4
C# 3.0
• Implicitly typed local variables• Object and collection initializers• Auto-properties• Anonymous types• Extension methods• Query expressions• Lambda expressions• Expression trees• And more..
Page
5
C# 4.0
• Dynamic binding• Named and optional parameters• Generic co- and contravariance• And more..
Page
6
C# 5.0
• Asynchronous methods using Async and Await• Caller info attributes
Page
7
The state of the Compiler
• It’s been a black box• Roslyn to the rescue!• .NET Compiler Platform• Microsoft decides to re-write the compiler• Compiler written in C#• Easier to extend and maintain• Open Source!
Page
/ Copyright ©2014 by Readify Pty Ltd 8
C# 6.0 Overview
• Auto-property initializers• Getter-only auto-properties• Assignment to getter-only auto-properties
from constructor • Parameter-less struct constructors• Using Statements for Static Members• Dictionary Initializer• Await in catch/finally• Exception filters• Expression-bodied members
› Null propagation› String interpolation› nameof operator› And more..
9
Page
Auto-Property Initializers
Page
10
Auto-property initializers in a nutshell
class Person{ public string Name { get; set; }}class Person{ public string Name { get; } = "Anonymous";}
= "Anonymous";
Page
11
Auto-property initializers in a nutshell
class Person{ public string Name { get; }
public Person() { Name = “Abhishek"; }}
Page
/ Copyright ©2014 by Readify Pty Ltd 12
Auto-property initializers in a nutshell
class Person{ private readonly string <Name>k__BackingField = “Abhishek";
public string Name { get { return this.<Name>k__BackingField; } }}
13
Page
Parameter-less struct constructors
Page
/ Copyright ©2014 by Readify Pty Ltd 14
Parameter-less struct constructors in a nutshell
@fekberg
struct Point{ public int X { get; } public int Y { get; }
}
Read Only!
public Point() { X = 100; Y = 100; }
Page
15
Parameter-less struct constructors in a nutshell
Read Only!
struct Point{ private readonly int <X>k__BackingField; private readonly int <Y>k__BackingField; public int X { get { return this.<X>k__BackingField; } } public int Y { get { return this.<Y>k__BackingField; } } public Point() { this.<X>k__BackingField = 100; this.<Y>k__BackingField = 100; }}
Page
16
Parameter-less struct constructors in a nutshell
Read Only!
struct Point{ public int X { get; } public int Y { get; }
public Point(int x, int y) { X = x; Y = y; }
public Point() : this(100, 100) { }}
17
Page
Using Statements for Static Members
Page
18
Using Statements for Static Members in a nutshell
class Program{ static void Main(string[] args) { var angle = 90d; Console.WriteLine(Math.Sin(angle)); }}
Page
19
Using Statements for Static Members in a nutshell
using System.Console;using System.Math;
class Program{ static void Main(string[] args) { var angle = 90d; WriteLine(Sin(angle)); }}
Page
20
Using Statements for Static Members in a nutshell
using System.Console;using System.Linq.Enumerable;
class Program{ static void Main(string[] args) { foreach (var i in Range(0, 10)) { WriteLine(i); } }}
Page
Dictionary Initializers
Page
22
Dictionary Initializers in a nutshellvar people = new Dictionary<string, Person>{ [“abhishek"] = new Person()};
var answers = new Dictionary<int, string>{ [42] = "the answer to life the universe and everything"};
Page
Await inside Finally block
Page
24
Await + Finally in a nutshellpublic async Task DownloadAsync(){
}
try { } catch { await Task.Delay(2000); } finally { await Task.Delay(2000); }
Page
Exception Filters
Page
26
Exception filters in a nutshelltry{ throw new CustomException { Severity = 100 };}catch (CustomException ex) if (ex.Severity > 50){ Console.WriteLine("*BING BING* WARNING *BING BING*");}catch (CustomException ex){ Console.WriteLine("Whooops!");}
Page
Null Propagation
Page
28
Null propagation in a nutshellclass Person{ public string Name { get; set; } public Address Address { get; set; }}
Console.WriteLine(abhishek.Address.AddressLine1);
var abhishe = new Person{ Name = “Abhishek"};
class Address{ public string AddressLine1 { get; set; } public string AddressLine2 { get; set; }}
Page
29
Null propagation in a nutshellclass Person{ public string Name { get; set; } public Address Address { get; set; }}
Console.WriteLine(abhishek.Address.AddressLine1);
var abhishek = new Person{ Name = “abhishek"};
class Address{ public string AddressLine1 { get; set; } public string AddressLine2 { get; set; }}
Page
30
Null propagation in a nutshellclass Person{ public string Name { get; set; } public Address Address { get; set; }}
Console.WriteLine(abhishek.Address.AddressLine1);Console.WriteLine(abhishek.Address == null ? "No Address" : abhishek.Address.AddressLine1);
var abhishek = new Person{ Name = “abhishek"};
class Address{ public string AddressLine1 { get; set; } public string AddressLine2 { get; set; }}
Page
31
Null propagation in a nutshellclass Person{ public string Name { get; set; } public Address Address { get; set; }}
Console.WriteLine(ahishek.Address.AddressLine1);Console.WriteLine(abhishek.Address == null ? "No Address" : abhishek.Address.AddressLine1);
Console.WriteLine(abhishek?.Address?.AddressLine1 ?? "No Address");
var abhishek = new Person{ Name = “abhishek"};
class Address{ public string AddressLine1 { get; set; } public string AddressLine2 { get; set; }}
Page
32
Null propagation in a nutshell
@fekberg
var people = new[]{ new Person(), null};
WriteLine(people[0]?.Name);
WriteLine(people[1]?.Name);
Page
33
Null propagation in a nutshellPerson[] people = null;WriteLine(people?[0]?.Name);
Person[] people = null;Console.WriteLine(
(people != null) ? ((people[0] == null) ? null : people[0].Name) : null
);
Page
Expression-bodied members
Page
35
Expression-bodied members in a nutshell
class Rectangle{ public double Width { get; set; } public double Height { get; set; }
public double Area => Width * Height;}
Page
36
Expression-bodied members in a nutshell
class Rectangle{ public double Width { get; set; } public double Height { get; set; }
public override string ToString() => "My Width is \{Width} and my Height is \{Height}";
}
Page
String interpolation
Page
38
String interpolation in a nutshellpublic override string ToString() =>
"My Width is \{Width} and my Height is \{Height}";
public override string ToString() => $"My Width is {Width} and my Height is {Height}";
Syntax will change in a later release to the following:
Page
39
String interpolation in a nutshellpublic override string ToString() =>
"My Width is \{Width} and my Height is \{Height}";
public override string ToString(){ object[] args = new object[] { this.Width, this.Height }; return string.Format("My Width is {0} and my Height is {1}", args);}
Page
40
String interpolation in a nutshellint age = 28;var result = "Hello there, I'm \{age : D5} years old!";WriteLine(result);
int num = 28;object[] objArray1 = new object[] { num };Console.WriteLine(string.Format("Hello there, I'm {0:D5} years old!", objArray1));
Page
nameof operator
Page
42
nameof operator in a nutshellstatic void Main(string[] args){ WriteLine("Parameter name is: \{nameof(args)}");}
Page
43
nameof operator in a nutshellpublic double CalculateArea(int width, int height){ if (width <= 0) {
throw new ArgumentException("Parameter \{nameof(width)} cannot be less than 0"); }
return width * height;}
44
Page
There’s more??
C# 7.0
Page
45
How to try?
• Install Visual Studio Preview 2 and create project with experimental compilation symbol.
Page
46
What about C# 7.0?
• Binary literals and Digit separators0b000010000xFF_00_FA_AF
Page
47
What about C# 7.0?
• Event initializersvar client = new WebClient{ DownloadFileCompleted +=
DownloadFileCompletedHandler};
Page
48
What about C# 7.0?
• Nested MethodsVoid MyMethod(){ void calculator(int x) { return x * 2; }; return calculator(10); }
Page
49
What about C# 7.0?
• Field targets on auto-properties [field: NonSerialized]public int Age { get; set; }
Page
50
What about C# 7.0?
• Inherent use of Tuples and language integration
(int x, int y) MyFunction(){ Console.WriteLine(“My Tuple is called”); }
Page
51
What about C# 7.0?Inherent use of Tuples and language integration
public class Person{ public readonly (string firstName, string lastName) Names; // a tuple public Person((string FirstName, string LastName)) names, int Age) { Names = names; }}
Page
52
What about C# 7.0?Inherent use of Tuples and language integration(string first, string last) = GetNames("Inigo Montoya")
Page
53
What about C# 7.0?
• Using params with IEnumerableint Avg(params IEnumerable<int> numbers)
Page
54
What about C# 7.0?
• Declaration Expressionspublic void CalculateAgeBasedOn(int birthYear, out int age){ age = DateTime.Now.Year - birthYear;}CalculateAgeBasedOn(1987, out var age);
Page
55
What about C# 7.0?
• Primary Constructors
class Person(string name, int age){ private string _name = name; private int _age = age;}
Page
56
What about C# 7.0?
• Pattern Matching
object obj;// ...switch(obj) { case 42: // ... case Color.Red: // ... case string s: // ... case Point(int x, 42) where (Y > 42): // ... case Point(490, 42): // fine // ... default: // ...}
Page
57
What about C# 7.0?
• Async Streams
• IAsyncEnumerable will also work with Await. It has MoveNextAsync and Current property like IEnumerable, and you can call them using foreach loops.
Page
58
What about C# 7.0?
• Immutable Objects
• Inherently thread-safe• Makes it easier to use and reason about code• Easier to parallelize your code• Reference to immutable objects can be cached, as they won’t change
public immutable class Point{ public Point(int x, int y) { x = x; Y = y; } public int X { get; } public int Y { get; }}
Page
60
Summary
• C# 6.0 is awesome• There’s a lot of change in C# 6.0• .NET Compiler Platform ("Roslyn") makes it easy
for Microsoft to improve the language• There’s a lot of interesting features that could go in
C# 7.0
61
Page
Questions?