+ All Categories
Home > Technology > C# 7.0 Hacks and Features

C# 7.0 Hacks and Features

Date post: 08-Feb-2017
Category:
Upload: abhishek-sur
View: 266 times
Download: 0 times
Share this document with a friend
60
C# 7.0 What?! C# is Being Updated? Abhishek Sur, Microsoft MVP Architect, Insync
Transcript
Page 1: C# 7.0 Hacks and Features

C# 7.0What?! C# is Being Updated?

Abhishek Sur, Microsoft MVPArchitect, Insync

Page 2: C# 7.0 Hacks and Features

2

Page

History of C#

Page 3: C# 7.0 Hacks and Features

Page

3

C# 2.0

• Generics• Partial types• Anonymous methods• Iterators• Nullable types• Getter/Setter separate accessibility• Static classes• And more..

Page 4: C# 7.0 Hacks and Features

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# 7.0 Hacks and Features

Page

5

C# 4.0

• Dynamic binding• Named and optional parameters• Generic co- and contravariance• And more..

Page 6: C# 7.0 Hacks and Features

Page

6

C# 5.0

• Asynchronous methods using Async and Await• Caller info attributes

Page 7: C# 7.0 Hacks and Features

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 8: C# 7.0 Hacks and Features

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

Page 9: C# 7.0 Hacks and Features

9

Page

Auto-Property Initializers

Page 10: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

Page

11

Auto-property initializers in a nutshell

class Person{ public string Name { get; }

public Person() { Name = “Abhishek"; }}

Page 12: C# 7.0 Hacks and Features

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

Page 13: C# 7.0 Hacks and Features

13

Page

Parameter-less struct constructors

Page 14: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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

Page 17: C# 7.0 Hacks and Features

17

Page

Using Statements for Static Members

Page 18: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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 21: C# 7.0 Hacks and Features

Page

Dictionary Initializers

Page 22: C# 7.0 Hacks and Features

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 23: C# 7.0 Hacks and Features

Page

Await inside Finally block

Page 24: C# 7.0 Hacks and Features

Page

24

Await + Finally in a nutshellpublic async Task DownloadAsync(){

}

try { } catch { await Task.Delay(2000); } finally { await Task.Delay(2000); }

Page 25: C# 7.0 Hacks and Features

Page

Exception Filters

Page 26: C# 7.0 Hacks and Features

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 27: C# 7.0 Hacks and Features

Page

Null Propagation

Page 28: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

Page

32

Null propagation in a nutshell

@fekberg

var people = new[]{ new Person(), null};

WriteLine(people[0]?.Name);

WriteLine(people[1]?.Name);

Page 33: C# 7.0 Hacks and Features

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 34: C# 7.0 Hacks and Features

Page

Expression-bodied members

Page 35: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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 37: C# 7.0 Hacks and Features

Page

String interpolation

Page 38: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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 41: C# 7.0 Hacks and Features

Page

nameof operator

Page 42: C# 7.0 Hacks and Features

Page

42

nameof operator in a nutshellstatic void Main(string[] args){ WriteLine("Parameter name is: \{nameof(args)}");}

Page 43: C# 7.0 Hacks and Features

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

Page 44: C# 7.0 Hacks and Features

44

Page

There’s more??

C# 7.0

Page 45: C# 7.0 Hacks and Features

Page

45

How to try?

• Install Visual Studio Preview 2 and create project with experimental compilation symbol.

Page 46: C# 7.0 Hacks and Features

Page

46

What about C# 7.0?

• Binary literals and Digit separators0b000010000xFF_00_FA_AF

Page 47: C# 7.0 Hacks and Features

Page

47

What about C# 7.0?

• Event initializersvar client = new WebClient{ DownloadFileCompleted +=

DownloadFileCompletedHandler};

Page 48: C# 7.0 Hacks and Features

Page

48

What about C# 7.0?

• Nested MethodsVoid MyMethod(){ void calculator(int x) { return x * 2; }; return calculator(10); }

Page 49: C# 7.0 Hacks and Features

Page

49

What about C# 7.0?

• Field targets on auto-properties [field: NonSerialized]public int Age { get; set; }

Page 50: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

Page

52

What about C# 7.0?Inherent use of Tuples and language integration(string first, string last) = GetNames("Inigo Montoya")

Page 53: C# 7.0 Hacks and Features

Page

53

What about C# 7.0?

• Using params with IEnumerableint Avg(params IEnumerable<int> numbers)

Page 54: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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: C# 7.0 Hacks and Features

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 59: C# 7.0 Hacks and Features

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

Page 60: C# 7.0 Hacks and Features

61

Page

Questions?


Recommended