tuga it 2017 - whats new in c# 7

28
TUGA IT 2017 LISBON, PORTUGAL

Upload: paulo-morgado

Post on 18-Mar-2018

270 views

Category:

Technology


9 download

TRANSCRIPT

Page 1: Tuga IT 2017 - Whats new in C# 7

TUGA IT 2017LISBON, PORTUGAL

Page 2: Tuga IT 2017 - Whats new in C# 7

THANK YOU TO OUR SPONSORSPLATINUM

GOLD SILVER

Page 3: Tuga IT 2017 - Whats new in C# 7

PARTICIPATING COMMUNITIESCLOUD PRO PT

Page 5: Tuga IT 2017 - Whats new in C# 7

Agenda

• Literal improvements• More expression bodied members• Throw expressions• Out variables• Pattern matching• Tuples• Local functions• Ref returns and locals• Generalized async return types

Page 6: Tuga IT 2017 - Whats new in C# 7

Literal improvements

var n = 123456789;var n = 0x075BCD15;

Binary Literalsvar n = 0b00000111010110111100110100010101;

Digit Separatorsvar d = 123_456_789;

var x = 0x075B_CD15;

var b = 0b0000_0111_0101_1011_1100_1101_0001_0101;

0b_0000_0111_0101_1011_1100_1101_0001_0101_;

0b0000__0111__0101__1011__1100__1101__0001__0101;

Page 7: Tuga IT 2017 - Whats new in C# 7

More expression bodied members

class Person{

private static ConcurrentDictionary<int, string> names= new ConcurrentDictionary<int, string>();

private int id = GetId();public Person(string name) => names.TryAdd(id, name); // constructors~Person() => names.TryRemove(id, out _); // destructorspublic string Name{

get => names[id]; // gettersset => names[id] = value; // setters

}}

Page 8: Tuga IT 2017 - Whats new in C# 7

Throw expressions

class Person{

public string Name { get; }public Person(string name)

=> Name = name ?? throw new ArgumentNullException(nameof(name));public string GetFirstName(){

var parts = Name.Split(" ");return (parts.Length > 0)

? parts[0]: throw new InvalidOperationException("No name!");

}public string GetLastName() => throw new NotImplementedException();

}

Page 9: Tuga IT 2017 - Whats new in C# 7

Out variables

public void PrintCoordinates(Point p){

int x, y;p.GetCoordinates(out x, out y);WriteLine($"({x}, {y})");

}

public void PrintCoordinates(Point p){

p.GetCoordinates(out int x, out int y);WriteLine($"({x}, {y})");

}

public void PrintCoordinates(Point p){

p.GetCoordinates(out var x, out var y);WriteLine($"({x}, {y})");

}

Page 10: Tuga IT 2017 - Whats new in C# 7

Out variables - disacards

public void PrintCoordinates(Point p){

p.GetCoordinates(out var x, out _);WriteLine($"{x}");

}

Page 11: Tuga IT 2017 - Whats new in C# 7

Pattern matching

public void PrintStars(object o){

if (o is null) return; // constant pattern "null"if (!(o is int i)) return; // type pattern "int i"WriteLine(new string('*', i));

}

if (o is int i || (o is string s && int.TryParse(s, out i))){

/* use i */}

Page 12: Tuga IT 2017 - Whats new in C# 7

Pattern matchingswitch (shape){

case Ellipse e:WriteLine($"It's a {e.Height} x {e.Width} ellipse.");break;

case Rectangle r:WriteLine($"{r.Height} x {r.Width} rectangle");break;

default:WriteLine("<unknown shape>");break;

case null:throw new ArgumentNullException(nameof(shape));

}

switch (shape){

case Ellipse c when c.Height == c.Width:WriteLine($"It's a {c.Height} circle.");break;

case Ellipse e:WriteLine($"It's a {e.Height} x {e.Width} ellipse.");break;

case Rectangle s when (s.Height == s.Width):WriteLine($"It's a {s.Height} square");break;

case Rectangle r:WriteLine($"It's a {r.Height} x {r.Width} rectangle");break;

default:WriteLine("<unknown shape>");break;

case null:throw new ArgumentNullException(nameof(shape));

}

Page 13: Tuga IT 2017 - Whats new in C# 7

Tuples

Tuple<string, string, string> LookupName(long id) // tuple return type{

// retrieve first, middle and last from data storagereturn Tuple.Create(first, middle, last); // tuple value

}

var names = LookupName(id);WriteLine($"found {names.Item1} {names.Item3}.");

(string, string, string) LookupName(long id) // tuple return type{

// retrieve first, middle and last from data storagereturn (first, middle, last); // tuple literal

}

var names = LookupName(id);WriteLine($"found {names.Item1} {names.Item3}.");

(string first, string middle, string last) LookupName(long id) // tuple return type{

// retrieve first, middle and last from data storagereturn (first, middle, last); // tuple literal

}

var names = LookupName(id);WriteLine($"found {names.first} {names.last}.");

Page 14: Tuga IT 2017 - Whats new in C# 7

Tuples

// named tuple elements in a literal;var names = (first: first, middle: middle, last: last);WriteLine($"found {names.first} {names.last}.");

Page 15: Tuga IT 2017 - Whats new in C# 7

Tuples - deconstruction

(string first, string middle, string last) LookupName(long id)

// deconstructing declaration(string first, string middle, string last) = LookupName(id);WriteLine($"found {first} {last}.");

(string first, string middle, string last) LookupName(long id)

// var inside(var first, var middle, var last) = LookupName(id);WriteLine($"found {first} {last}.");

(string first, string middle, string last) LookupName(long id)

// var outsidevar (first, middle, last) = LookupName(id);WriteLine($"found {first} {last}.");

Page 16: Tuga IT 2017 - Whats new in C# 7

Tuple - deconstruction

class Point{

public int X { get; }public int Y { get; }public Point(int x, int y) { X = x; Y = y; }public void Deconstruct(out int x, out int y) { x = X; y = Y; }

}

(var myX, var myY) = GetPoint();

(var myX, _) = GetPoint(); // I only care about myX

// calls Deconstruct(out myX, out myY);

Page 17: Tuga IT 2017 - Whats new in C# 7

Tuples

• Tuples are value types, and their elements are simply public, mutable fields. They have value equality, meaning that two tuples are equal (and have the same hash code) if all their elements are pairwise equal (and have the same hash code).

• This makes tuples useful for many other situations beyond multiple return values. For instance, if you need a dictionary with multiple keys, use a tuple as your key and everything works out right. If you need a list with multiple values at each position, use a tuple, and searching the list etc. will work correctly.

• Tuples rely on a family of underlying generic struct types called ValueTuple<...>. If you target a Framework that doesn’t yet include those types, you can instead pick them up from NuGet:

• Right-click the project in the Solution Explorer and select "Manage NuGet Packages…"

• Select the "Browse" tab and select "nuget.org" as the "Package source"• Search for "System.ValueTuple" and install it.

Page 18: Tuga IT 2017 - Whats new in C# 7

public int Fibonacci(int x){

if (x < 0) throw new ArgumentException("Less negativity please!", nameof(x));return Fib(x).current;

}

private (int current, int previous) Fib(int i){

if (i == 0) return (1, 0);var (p, pp) = Fib(i - 1);return (p + pp, p);

}

Local functions

public int Fibonacci(int x){

if (x < 0) throw new ArgumentException("Less negativity please!", nameof(x));return Fib(x).current;

(int current, int previous) Fib(int i){

if (i == 0) return (1, 0);var (p, pp) = Fib(i - 1);return (p + pp, p);

}}

Page 19: Tuga IT 2017 - Whats new in C# 7

Local functionsprivate string Tweetify(string msg){

if (msg.Length >= TweetSize) return msg.Substring(0, TweetSize - 3) + "...";

var sb = new StringBuilder(msg);var random = new Random();

while (TryAddHashTag()) { }

return sb.ToString();

bool TryAddHashTag(){

var r = random.Next(0, Hashtags.Length);var hashtag = " " + Hashtags[r];

if (sb.Length + hashtag.Length > TweetSize) return false;sb.Append(hashtag);return true;

}}

Page 20: Tuga IT 2017 - Whats new in C# 7

Local functions

public IEnumerable<T> Filter<T>(IEnumerable<T> source, Func<T, bool> filter){

if (source == null) throw new ArgumentNullException(nameof(source));if (filter == null) throw new ArgumentNullException(nameof(filter));

return Iterator();

IEnumerable<T> Iterator(){

foreach (var element in source){

if (filter(element)) { yield return element; }}

}}

Page 21: Tuga IT 2017 - Whats new in C# 7

Local functions

public async Task<IActionResult> Index(int i){

return await GetStuffAsync();

async Task<IActionResult> GetStuffAsync(){

var someStuff = await GetSomeStuffAsync(i).ConfigureAwait(false);var moreStuff = await GetMoreStuffAsync(i).ConfigureAwait(false);/// ...return result;

}}

Page 22: Tuga IT 2017 - Whats new in C# 7

Ref returns and locals

public ref int Find(int number, int[] numbers){

for (int i = 0; i < numbers.Length; i++){

if (numbers[i] == number){

return ref numbers[i]; // return the storage location, not the value}

}throw new IndexOutOfRangeException($"{nameof(number)} not found");

}

int[] array = { 1, 15, -39, 0, 7, 14, -12 };ref int place = ref Find(7, array); // aliases 7's place in the arrayplace = 9; // replaces 7 with 9 in the arrayWriteLine(array[4]); // prints 9

Page 23: Tuga IT 2017 - Whats new in C# 7

Generalized async return types

public async Task<int> GetValueAsync(){

return await GetValueMyAsync();}

private abstract MyTask<int> GetValueMyAsync();

public class MyTask<T>{

public MyAwaitable<T> GetAwaiter();}

public class MyAwaitable<T> : INotifyCompletion{

public bool IsCompleted { get; }public T GetResult();public void OnCompleted(Action continuation);

}

public class MyAwaitable<T> : INotifyCompletion, ICriticalNotifyCompletion{

public bool IsCompleted { get; }public T GetResult();public void OnCompleted(Action continuation);public void UnsafeOnCompleted(Action continuation);

}

Page 24: Tuga IT 2017 - Whats new in C# 7

Generalized async return types[AsyncMethodBuilder(typeof(MyAsyncMethodBuilder<>))]public class MyTask<T>{

public MyAwaitable<T> GetAwaiter();}

public class MyAsyncMethodBuilder<T1>{

public static MyAsyncMethodBuilder<T> Create();public void Start<TStateMachine>(ref TStateMachine stateMachine)

where TStateMachine : IAsyncStateMachine;public void SetStateMachine(IAsyncStateMachine stateMachine);public void SetException(Exception exception);public void SetResult(T result);public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)

where TAwaiter : INotifyCompletionwhere TStateMachine : IAsyncStateMachine;

public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)where TAwaiter : ICriticalNotifyCompletionwhere TStateMachine : IAsyncStateMachine;

public MyTask<T> Task { get; }}

Page 25: Tuga IT 2017 - Whats new in C# 7

Generalized async return types

Up until now, async methods in C# must either return void, Task or Task<T>. C# 7.0 allows other types to be defined in such a way that they can be returned from an async method.

For instance we now have a ValueTask<T> struct type. It is built to prevent the allocation of a Task<T> object in cases where the result of the async operation is already available at the time of awaiting. For many async scenarios where buffering is involved for example, this can drastically reduce the number of allocations and lead to significant performance gains.

There are many other ways that you can imagine custom "task-like" types being useful. It won’t be straightforward to create them correctly, so we don’t expect most people to roll their own, but it is likely that they will start to show up in frameworks and APIs, and callers can then just return and await them the way they do Tasks today.

Page 26: Tuga IT 2017 - Whats new in C# 7

Resources

• What's new in C# 7• https://docs.microsoft.com/dotnet/articles/csharp/whats-new/csharp-7

• New Features in C# 7.0• https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/

• C# Language Design• https://github.com/dotnet/csharplang/

• .NET Compiler Platform ("Roslyn")• https://github.com/dotnet/roslyn

• Visual Studio 2017• https://www.visualstudio.com/vs/whatsnew/

• LINQPad• http://www.linqpad.net/

Page 27: Tuga IT 2017 - Whats new in C# 7

PLEASE FILL IN EVALUATION FORMSFRIDAY, MAY 19th SATURDAY, MAY 20th

https://survs.com/survey/cprwce7pi8 https://survs.com/survey/l9kksmlzd8

YOUR OPINION IS IMPORTANT!

Page 28: Tuga IT 2017 - Whats new in C# 7

THANK YOU TO OUR SPONSORSPLATINUM

GOLD SILVER