SlideShare a Scribd company logo
1 of 64
Download to read offline
C# - What’s next?
@christiannagel
C# Strategie
Laufende Erweiterungen
Geänderte Bedürfnisse erfüllen
Agenda
C#
Strategie
C#
Today
C#
Future
Christian Nagel
• Training
• Coaching
• Consulting
• Development
• Microsoft MVP
• www.cninnovation.com
• csharp.christiannagel.com
Schnell Innovationen einführen
Aber im Geist von C#
Ziele mit C#
7.1, 7.2, 7.3
• Garbage Collection vermeiden
• Kopieren vermeiden
• "Safe" Code
Sicherer,
effizienter
Code
• Zusätzliche Möglichkeiten
Mehr
Freiheiten
• "Sag es kürzer"
Weniger
Code
C# 8
Magisch
C# 7.x Today
C# 7.0
Tuples &
Deconstruction
Pattern
Matching
Expressions
everywhere
Reference
Semantics
Tuples
• Werte unterschiedlicher Typen kombinieren
• Strong Names
• Value Types var t1 = (n: 42, s: "magic");
int i1 = t1.n;
string s1 = t1.s;
Deconstruction
• Create parts from objects or tuples
• Implement method Deconstruct
var p1 = new Person("Tom", "Turbo");
(string firstName, string lastName) = p1;
Pattern Matching (C# 7.0)
• is Operator and switch statement extended
• Const Pattern
• Type Pattern
• Var Pattern
public void IsSample(object o)
{
if (o is 42)
{
}
if (o is Person p)
{
}
if (o is var v1)
{
}
}
public void PatternMatchingWithSwitchStatement(object o)
{
switch (o)
{
case 42:
break;
case Person p when p.FirstName == "Katharina":
break;
case Person p:
break;
case var v:
break;
}
}
C# 7.1
• Async main
• Generics pattern match
• Infer tuple names
• Target typed default
static async Task Main()
{
await FooAsync();
}
public void Send<T>(T packet)
where T : Packet
{
if (packet is KeepalivePacket keepalive)
{
}
var t1 = (racer.FirstName, racer.Wins);
int wins = t1.Wins;
ImmutableArray<int> arr = default(ImmutableArray<int>);ImmutableArray<int> arr = default;
C# 7.2
• Leading Separator
• Non-trailing named arguments
• private protected
• Conditional Ref
• readonly ref
• Span Safety
ushort b1 = 0b_1010_1111_0101_0000;
if (Enum.TryParse(day, ignoreCase: true,
out DayOfWeek weekday))
{
reservation.Weekday = weekday;
}
C# 7.3
• Auto Property Field Attributes
• Generic constraints
• unmanaged, Enum, Delegate
• Expression Variables in Initializers
• Pattern-based fixed statement
• Ref local reassignment
• Stackalloc array initializers
[Serializable]
public class Foo
{
[field: NonSerialized]
public string MySecret { get; set; }
}
void Hash<T>(T value) where T : unmanaged
{
}
var d1 = stackalloc int[3] { 1, 2, 3 };
var d2 = stackalloc int[] { 1, 2, 3 };
var d3 = stackalloc[] { 1, 2, 3 };
C# 7 Point Releases
• Sicherer, effizienter Code
• Mehr Freiheiten
• Weniger Code
C# 8
State
Proposal
Discussed/Decision in LDM
Prototype
Implementation in Progress
Implemented
State: Implemented
• Default literal deconstruction
• Alternative interpolated verbatim strings
(int i, string j) = (default, default); // C# 7
(int i, string j) = default; // C# 8
var foo = $@"c:foo{someFile}" // C# 7
var foo = @$"c:foo{someFile}" // C# 8
State: In Progress
• Generic attributes
• Relax ordering ref and partial modifiers
• Null coalescing assignment
• Async streams
• Ranges
• Records
public class ValidationAttribute<T> : Attribute
{
}
if (variable == null) // C# 7
{
variable = expression;
}
Variable ??= expression; // C# 8
public ref partial class { } // C# 7
public partial ref class { } // C# 8
State: Prototype
• Caller expression attribute
• Target-typed new
• Pattern-based using
• Default interface methods
• Nullable reference type
• Recursive patterns
// C# 7
private Dictionary<string, List<int>> field =
new Dictionary<string, List<int>>()
{
{ "item1", new int[] { 1, 2, 3 } }
};
// C# 8
private Dictionary<string, List<int>> field =
new()
{
{ "item1", new() { 1, 2, 3 } }
};
public static class Debug
{
public static void Assert(bool condition,
[CallerArgumentExpression("condition")] string message = null);
}
Debug.Assert(array.Length == 1);
Debug.Assert(array.Length == 1, "array.Length == 1");
Default
Interface
Methods
Ändern von Interfaces ohne
Breaking Changes
Traits – Wiederverwendbarkeit
von Methoden in
unabhängigen Klassen
Basiert auf Java's Default
Methods
Default Interface Methods
• Changing the interface without breaking changes
public interface ILogger
{
void Log(string message);
}
public interface ILogger
{
void Log(string message);
void Log(Exception ex) => Log(ex.Message);
}
public class MyLogger : ILogger
{
public void Log(string message) => Console.WriteLine(message);
}
Default Interface
Methods
Allowed
Modifiers
private, protected, internal, public,
virtual, abstract, override, sealed, static,
extern
Default Interface Methods
Mehrfachvererbung mit Interfaces?
interface I0
{
void M() => Console.WriteLine("I0");
}
interface I2 : I0
{
override void M() => Console.WriteLine("I2");
}
interface I1 : I0
{
override void M() => Console.WriteLine("I1");
}
interface I3 : I1, I2
{
void I0.M() => I2.base.M();
}
Default Interface Methods
Most specific override Rule
interface I0
{
void M() => Console.WriteLine("I0");
}
interface I2 : I0
{
override void M() => Console.WriteLine("I2");
}
interface I1 : I0
{
override void M() => Console.WriteLine("I1");
}
// error – no most specific override rule for IA.M
interface I3 : I1, I2 { }
// error – no most specific override rule for IA.M
abstract class C : I1, I2 { }
abstract class C : I1, I2
{
public abstract void M();
}
Default Interface Methods
Re-Abstract
interface I0
{
void M();
}
interface I2 : I0
{
override void M();
}
interface I1 : I0
{
override void M() => Console.WriteLine("I1");
}
Async Streams
• async/await liefert ein Ergebnis
• Async Streams erweitert async/await mit
Stream von Ergebnissen
• Asynchronous Datenquellen die vom Consumer
kontrolliert werden
• Alternative zu System.Reactive
Async Streams
• IAsyncDisposable
• IAsyncEnumerable
• IAsyncEnumerator
public interface IAsyncDisposable
{
Task DisposeAsync();
}
public interface IAsyncEnumerable<out T>
{
IAsyncEnumerator<T> GetAsyncEnumerator();
}
public interface IAsyncEnumerator<out T> :
IAsyncDiposable
{
Task<bool> MoveNextAsync();
T Current { get; }
}
Using Async Streams
• foreach await
IAsyncEnumerator<T> enumerator =
enumerable.GetAsyncEnumerator();
try
{
while (await enumerator.MoveNextAsync())
{
Use(enumerator.Current);
}
}
finally
{
await enumerator.DisposeAsync();
}
foreach await (var i in enumerable)
{
Use(i);
}
Async with yield
• return IAsyncEnumerable static async IAsyncEnumerable<int> MyIterator()
{
try
{
for (int i = 0; i < 100; i++)
{
await Task.Delay(1000);
yield return i;
}
}
finally
{
await Task.Delay(200);
Console.WriteLine("finally");
}
}
Async Streams
Open
Questions
• LINQ
• ~600 neue Methoden
wären erfoderlich
• Interactive Extensions (Ix)
implementiert viele
• => Support Community
extend Ix
• Integration mit IObservable<T>
• Integration auf Library-
Ebene
Records
Einfachere Deklaration
für Klassen und
Structs (Immutable)
Caller-Receiver
Parameters
With Expressions
Declare Records
public struct Pair(object First, object Second);
Record Implementation
• Implements
• IEquatable
• GetHashCode
• Deconstruct
• With
public struct Pair(object First, object Second);
public struct Pair : IEquatable<Pair>
{
public object First { get; }
public object Second { get; }
public Pair(object First, object Second)
{
this.First = First;
this.Second = Second;
}
public bool Equals(Pair other) =>
Equals(First, other.First) && Equals(Second, other.Second);
public override bool Equals(object other) =>
(other as Pair)?.Equals(this) == true;
public override int GetHashCode() =>
(First?.GetHashCode()*17 + Second?.GetHashCode()).GetValueOrDefault();
public Pair With(object First = this.First, object Second = this.Second) =>
new Pair(First, Second);
public void Deconstruct(out object First, out object Second)
{
First = this.First;
Second = this.Second;
}
}
var p1 = new Pair("one", "two");
var p2 = p1.With(First: "alpha");
Caller-Receiver Parameter
class Point
{
public readonly int X;
public readonly int Y;
public Point With(int x = this.X, int y = this.Y) =>
new Point(x, y);
//...
}
var p = new Point(3, 4);
p = p.With(x: 1);
With Expression
var p = new Point(3, 4);
p = p with { x = 1 };
// p = p.With(x: 1);
Indexes and
Ranges
New Operators
^ Hat Operator
.. Range
Operator
Index und Range &
Extensions
Hat Operator
int[] arr = { 1, 2, 3 };
int lastItem = arr[^1];
Slice
string text1 = "the quick brown fox jumped over the lazy dogs";
string text2 = text1[4..8];
string text3 = text1[^4..^1];
string text4 = text1[10..];
string text5 = text1[..8];
string text6 = text1[..];
More Uses
• switch, foreach
switch (codePoint)
{
case 1536..1541:
break;
foreach (var item in 3..5)
{
Patterns
Extended
• Always match
Discard Pattern
• Match für Property Werte
Property Pattern
• Match für innere Properties
Recursive Pattern
• Moderner switch Syntax
switch Expression
Pattern Matching Now
static string M1(Shape shape)
{
switch (shape)
{
case Shape s when s.Size.height > 100:
return $"large shape with size {s.Size} at position {s.Position}";
case Ellipse e:
return $"Ellipse with size {e.Size} at position {e.Position}";
case Rectangle r:
return $"Rectangle with size {r.Size} at position {r.Position}";
default:
return "another shape";
}
}
switch Expression
static string M2(Shape shape) =>
shape switch
{
Shape s when s.Size.height > 100 =>
$"large shape with size {s.Size} at position {s.Position}",
Ellipse e =>
$"Ellipse with size {e.Size} at position {e.Position}",
Rectangle r =>
$"Rectangle with size {r.Size} at position {r.Position}",
_ => "another shape"
}
};
Recursive, Property, and Discard Patterns
static string M3(Shape shape) =>
shape switch
{
CombinedShape (var shape1, var (pos, _)) =>
$"combined shape - shape1: {shape1.Name}, pos of shape2: {pos}",
{ Size: (200, 200), Position: var pos } =>
$"shape with size 200x200 at position {pos.x}:{pos.y}",
Ellipse (var pos, var size) =>
$"Ellipse with size {size} at position {pos}",
Rectangle (_, var size) => $"Rectangle with size {size}",
_ => "another shape"
};
Null
References
Most common .NET Exception
NullReferenceException
Billion Dollar Mistake
1965 in Algol
by Tony Hoare
"Billion Dollar
Mistake"
Null Conditional Operator (C# 6)
• Reduce Null-Checks
int? length = customers?.Length;
Customer first = customers?[0];
int? count = customers?[0]?.Orders?.Count();
public void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
Coalescing Operator (C# 5)
• Default values for null
int length = customers?.Length ?? 0;
public bool CanExecute(object parameter) =>
_canExecute?.Invoke() ?? true;
Nullable
Reference
Types
• Hilft finden von Bugs,
aber keine Garantie!
• Flow analysis - tracks nullable
reference variables
• Breaks existing code (opt-in)
• Nullability implemented with
metadata (ignored by downlevel
compilers)
• string, T non-nullable
• string?, T? nullable
Declare Nullable Reference Types
• Default to non-nullable
• ? to make reference type nullable
class Book
{
public Book(string title, string? isbn = null)
{
Title = title;
Isbn = isbn;
}
public string Title; // not null
public string? Isbn; // may be null
}
Using nullable reference type
void M1(string? ns)
{
Console.WriteLine(ns.Length); // compiler warning
void M2(string? ns)
{
if (ns == null) throw new ArgumentNullException(nameof(ns));
Console.WriteLine(ns.Length); // ok, not null
ns = null;
Console.WriteLine(ns.Length); // compiler warning
void M3(string? ns)
{
if (ns != null)
{
Console.WriteLine(ns.Length); // ok
Using non-nullable reference type
void M1(string ns)
{
Console.WriteLine(ns.Length); // ok
void M2(Book b)
{
b.Title = null; // warning
string isbn = b.Isbn; // warning – may be null
string title = b.Title; // ok
Compatibility
• Enable this in your own speed
// Enable assembly-level
[module: NonNullTypes]
[NonNullTypes(false)]
public class Foo
{
}
Summary
C# 8
Nullable Reference Types
Indexes and Ranges
Async Streams
Magic
Questions?
What's next –
Try it out!
• https://github.com/dotnet/csharplang/wiki/Nullable-
Reference-Types-Preview
• Visual Studio 2017 15.5-15.8 (funktioniert nicht mit
15.8.4, 15.8.5)
Nullable Reference Types
• https://github.com/dotnet/csharplang/wiki/vNext-
Preview
• Visual Studio 2017 15.5-15.7
Patterns und Ranges
• https://github.com/dotnet/roslyn
Andere Features
More Information
• https://github.com/ProfessionalCSharp
• https://csharp.christiannagel.com
• https://www.cninnovation.com
• Training & Coaching
Thank you!

More Related Content

What's hot

Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 

What's hot (20)

Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspective
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
 
Python tour
Python tourPython tour
Python tour
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Trafaret: monads and python
Trafaret: monads and pythonTrafaret: monads and python
Trafaret: monads and python
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 

Similar to C# - What's next

Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 

Similar to C# - What's next (20)

C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)
 
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
 
Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"
 
State of the .Net Performance
State of the .Net PerformanceState of the .Net Performance
State of the .Net Performance
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
C# - What's Next?
C# - What's Next?C# - What's Next?
C# - What's Next?
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
C++ process new
C++ process newC++ process new
C++ process new
 
Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Session 4
Session 4Session 4
Session 4
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
Hadoop Puzzlers
Hadoop PuzzlersHadoop Puzzlers
Hadoop Puzzlers
 
Hadoop Puzzlers
Hadoop PuzzlersHadoop Puzzlers
Hadoop Puzzlers
 
C
CC
C
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
Modern C++
Modern C++Modern C++
Modern C++
 
C# 8 in Libraries and Applications
C# 8 in Libraries and ApplicationsC# 8 in Libraries and Applications
C# 8 in Libraries and Applications
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 

More from Christian Nagel

More from Christian Nagel (19)

Async streams
Async streamsAsync streams
Async streams
 
C# 9 and 10 - What's cool?
C# 9 and 10 - What's cool?C# 9 and 10 - What's cool?
C# 9 and 10 - What's cool?
 
Azure App Configuration with .NET applications
Azure App Configuration with .NET applicationsAzure App Configuration with .NET applications
Azure App Configuration with .NET applications
 
C# 9 - What's the cool stuff? - BASTA! Spring 2021
C# 9 - What's the cool stuff? - BASTA! Spring 2021C# 9 - What's the cool stuff? - BASTA! Spring 2021
C# 9 - What's the cool stuff? - BASTA! Spring 2021
 
.NET Core Foundations - Dependency Injection, Logging & Configuration - BASTA...
.NET Core Foundations - Dependency Injection, Logging & Configuration - BASTA....NET Core Foundations - Dependency Injection, Logging & Configuration - BASTA...
.NET Core Foundations - Dependency Injection, Logging & Configuration - BASTA...
 
C# 8 in Libraries and Applications - BASTA! Frankfurt 2020
C# 8 in Libraries and Applications - BASTA! Frankfurt 2020C# 8 in Libraries and Applications - BASTA! Frankfurt 2020
C# 8 in Libraries and Applications - BASTA! Frankfurt 2020
 
Entity Framework Core 1.x/2.x Advanced
Entity Framework Core 1.x/2.x AdvancedEntity Framework Core 1.x/2.x Advanced
Entity Framework Core 1.x/2.x Advanced
 
Gemeinsame View-Models mit XAML Technologien
Gemeinsame View-Models mit XAML TechnologienGemeinsame View-Models mit XAML Technologien
Gemeinsame View-Models mit XAML Technologien
 
C# 8 and .NET Core 3
C# 8 and .NET Core 3C# 8 and .NET Core 3
C# 8 and .NET Core 3
 
.NET Core 3.0 - What's new?
.NET Core 3.0 - What's new?.NET Core 3.0 - What's new?
.NET Core 3.0 - What's new?
 
Adaptive Cards - User Interfaces with JSON
Adaptive Cards - User Interfaces with JSONAdaptive Cards - User Interfaces with JSON
Adaptive Cards - User Interfaces with JSON
 
Reference Semantik mit C# und .NET Core - BASTA 2019
Reference Semantik mit C# und .NET Core - BASTA 2019Reference Semantik mit C# und .NET Core - BASTA 2019
Reference Semantik mit C# und .NET Core - BASTA 2019
 
Blazor - The New Silverlight?
Blazor - The New Silverlight?Blazor - The New Silverlight?
Blazor - The New Silverlight?
 
Desktop Bridge with WPF - One way to build modern apps with WPF
Desktop Bridge with WPF - One way to build modern apps with WPFDesktop Bridge with WPF - One way to build modern apps with WPF
Desktop Bridge with WPF - One way to build modern apps with WPF
 
Reference Semantics with C# and .NET Core
Reference Semantics with C# and .NET CoreReference Semantics with C# and .NET Core
Reference Semantics with C# and .NET Core
 
Business Apps with the Universal Windows Platform
Business Apps with the Universal Windows PlatformBusiness Apps with the Universal Windows Platform
Business Apps with the Universal Windows Platform
 
Blazor - The New Silverlight?
Blazor - The New Silverlight?Blazor - The New Silverlight?
Blazor - The New Silverlight?
 
Was is Docker? Or: Docker for Software Developers
Was is Docker? Or: Docker for Software DevelopersWas is Docker? Or: Docker for Software Developers
Was is Docker? Or: Docker for Software Developers
 
Moderne Business Apps mit XAML - oder mit WPF für die Zukunft geplant
Moderne Business Apps mit XAML - oder mit WPF für die Zukunft geplantModerne Business Apps mit XAML - oder mit WPF für die Zukunft geplant
Moderne Business Apps mit XAML - oder mit WPF für die Zukunft geplant
 

Recently uploaded

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Recently uploaded (20)

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 

C# - What's next

  • 1. C# - What’s next? @christiannagel
  • 3.
  • 6. Christian Nagel • Training • Coaching • Consulting • Development • Microsoft MVP • www.cninnovation.com • csharp.christiannagel.com
  • 7.
  • 9.
  • 10.
  • 11. Ziele mit C# 7.1, 7.2, 7.3 • Garbage Collection vermeiden • Kopieren vermeiden • "Safe" Code Sicherer, effizienter Code • Zusätzliche Möglichkeiten Mehr Freiheiten • "Sag es kürzer" Weniger Code
  • 15. Tuples • Werte unterschiedlicher Typen kombinieren • Strong Names • Value Types var t1 = (n: 42, s: "magic"); int i1 = t1.n; string s1 = t1.s;
  • 16. Deconstruction • Create parts from objects or tuples • Implement method Deconstruct var p1 = new Person("Tom", "Turbo"); (string firstName, string lastName) = p1;
  • 17. Pattern Matching (C# 7.0) • is Operator and switch statement extended • Const Pattern • Type Pattern • Var Pattern public void IsSample(object o) { if (o is 42) { } if (o is Person p) { } if (o is var v1) { } } public void PatternMatchingWithSwitchStatement(object o) { switch (o) { case 42: break; case Person p when p.FirstName == "Katharina": break; case Person p: break; case var v: break; } }
  • 18. C# 7.1 • Async main • Generics pattern match • Infer tuple names • Target typed default static async Task Main() { await FooAsync(); } public void Send<T>(T packet) where T : Packet { if (packet is KeepalivePacket keepalive) { } var t1 = (racer.FirstName, racer.Wins); int wins = t1.Wins; ImmutableArray<int> arr = default(ImmutableArray<int>);ImmutableArray<int> arr = default;
  • 19. C# 7.2 • Leading Separator • Non-trailing named arguments • private protected • Conditional Ref • readonly ref • Span Safety ushort b1 = 0b_1010_1111_0101_0000; if (Enum.TryParse(day, ignoreCase: true, out DayOfWeek weekday)) { reservation.Weekday = weekday; }
  • 20. C# 7.3 • Auto Property Field Attributes • Generic constraints • unmanaged, Enum, Delegate • Expression Variables in Initializers • Pattern-based fixed statement • Ref local reassignment • Stackalloc array initializers [Serializable] public class Foo { [field: NonSerialized] public string MySecret { get; set; } } void Hash<T>(T value) where T : unmanaged { } var d1 = stackalloc int[3] { 1, 2, 3 }; var d2 = stackalloc int[] { 1, 2, 3 }; var d3 = stackalloc[] { 1, 2, 3 };
  • 21. C# 7 Point Releases • Sicherer, effizienter Code • Mehr Freiheiten • Weniger Code
  • 22. C# 8
  • 24. State: Implemented • Default literal deconstruction • Alternative interpolated verbatim strings (int i, string j) = (default, default); // C# 7 (int i, string j) = default; // C# 8 var foo = $@"c:foo{someFile}" // C# 7 var foo = @$"c:foo{someFile}" // C# 8
  • 25. State: In Progress • Generic attributes • Relax ordering ref and partial modifiers • Null coalescing assignment • Async streams • Ranges • Records public class ValidationAttribute<T> : Attribute { } if (variable == null) // C# 7 { variable = expression; } Variable ??= expression; // C# 8 public ref partial class { } // C# 7 public partial ref class { } // C# 8
  • 26. State: Prototype • Caller expression attribute • Target-typed new • Pattern-based using • Default interface methods • Nullable reference type • Recursive patterns // C# 7 private Dictionary<string, List<int>> field = new Dictionary<string, List<int>>() { { "item1", new int[] { 1, 2, 3 } } }; // C# 8 private Dictionary<string, List<int>> field = new() { { "item1", new() { 1, 2, 3 } } }; public static class Debug { public static void Assert(bool condition, [CallerArgumentExpression("condition")] string message = null); } Debug.Assert(array.Length == 1); Debug.Assert(array.Length == 1, "array.Length == 1");
  • 27. Default Interface Methods Ändern von Interfaces ohne Breaking Changes Traits – Wiederverwendbarkeit von Methoden in unabhängigen Klassen Basiert auf Java's Default Methods
  • 28. Default Interface Methods • Changing the interface without breaking changes public interface ILogger { void Log(string message); } public interface ILogger { void Log(string message); void Log(Exception ex) => Log(ex.Message); } public class MyLogger : ILogger { public void Log(string message) => Console.WriteLine(message); }
  • 29. Default Interface Methods Allowed Modifiers private, protected, internal, public, virtual, abstract, override, sealed, static, extern
  • 30. Default Interface Methods Mehrfachvererbung mit Interfaces? interface I0 { void M() => Console.WriteLine("I0"); } interface I2 : I0 { override void M() => Console.WriteLine("I2"); } interface I1 : I0 { override void M() => Console.WriteLine("I1"); } interface I3 : I1, I2 { void I0.M() => I2.base.M(); }
  • 31. Default Interface Methods Most specific override Rule interface I0 { void M() => Console.WriteLine("I0"); } interface I2 : I0 { override void M() => Console.WriteLine("I2"); } interface I1 : I0 { override void M() => Console.WriteLine("I1"); } // error – no most specific override rule for IA.M interface I3 : I1, I2 { } // error – no most specific override rule for IA.M abstract class C : I1, I2 { } abstract class C : I1, I2 { public abstract void M(); }
  • 32. Default Interface Methods Re-Abstract interface I0 { void M(); } interface I2 : I0 { override void M(); } interface I1 : I0 { override void M() => Console.WriteLine("I1"); }
  • 33. Async Streams • async/await liefert ein Ergebnis • Async Streams erweitert async/await mit Stream von Ergebnissen • Asynchronous Datenquellen die vom Consumer kontrolliert werden • Alternative zu System.Reactive
  • 34. Async Streams • IAsyncDisposable • IAsyncEnumerable • IAsyncEnumerator public interface IAsyncDisposable { Task DisposeAsync(); } public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(); } public interface IAsyncEnumerator<out T> : IAsyncDiposable { Task<bool> MoveNextAsync(); T Current { get; } }
  • 35. Using Async Streams • foreach await IAsyncEnumerator<T> enumerator = enumerable.GetAsyncEnumerator(); try { while (await enumerator.MoveNextAsync()) { Use(enumerator.Current); } } finally { await enumerator.DisposeAsync(); } foreach await (var i in enumerable) { Use(i); }
  • 36. Async with yield • return IAsyncEnumerable static async IAsyncEnumerable<int> MyIterator() { try { for (int i = 0; i < 100; i++) { await Task.Delay(1000); yield return i; } } finally { await Task.Delay(200); Console.WriteLine("finally"); } }
  • 37. Async Streams Open Questions • LINQ • ~600 neue Methoden wären erfoderlich • Interactive Extensions (Ix) implementiert viele • => Support Community extend Ix • Integration mit IObservable<T> • Integration auf Library- Ebene
  • 38. Records Einfachere Deklaration für Klassen und Structs (Immutable) Caller-Receiver Parameters With Expressions
  • 39. Declare Records public struct Pair(object First, object Second);
  • 40. Record Implementation • Implements • IEquatable • GetHashCode • Deconstruct • With public struct Pair(object First, object Second); public struct Pair : IEquatable<Pair> { public object First { get; } public object Second { get; } public Pair(object First, object Second) { this.First = First; this.Second = Second; } public bool Equals(Pair other) => Equals(First, other.First) && Equals(Second, other.Second); public override bool Equals(object other) => (other as Pair)?.Equals(this) == true; public override int GetHashCode() => (First?.GetHashCode()*17 + Second?.GetHashCode()).GetValueOrDefault(); public Pair With(object First = this.First, object Second = this.Second) => new Pair(First, Second); public void Deconstruct(out object First, out object Second) { First = this.First; Second = this.Second; } } var p1 = new Pair("one", "two"); var p2 = p1.With(First: "alpha");
  • 41. Caller-Receiver Parameter class Point { public readonly int X; public readonly int Y; public Point With(int x = this.X, int y = this.Y) => new Point(x, y); //... } var p = new Point(3, 4); p = p.With(x: 1);
  • 42. With Expression var p = new Point(3, 4); p = p with { x = 1 }; // p = p.With(x: 1);
  • 43. Indexes and Ranges New Operators ^ Hat Operator .. Range Operator Index und Range & Extensions
  • 44. Hat Operator int[] arr = { 1, 2, 3 }; int lastItem = arr[^1];
  • 45. Slice string text1 = "the quick brown fox jumped over the lazy dogs"; string text2 = text1[4..8]; string text3 = text1[^4..^1]; string text4 = text1[10..]; string text5 = text1[..8]; string text6 = text1[..];
  • 46. More Uses • switch, foreach switch (codePoint) { case 1536..1541: break; foreach (var item in 3..5) {
  • 47. Patterns Extended • Always match Discard Pattern • Match für Property Werte Property Pattern • Match für innere Properties Recursive Pattern • Moderner switch Syntax switch Expression
  • 48. Pattern Matching Now static string M1(Shape shape) { switch (shape) { case Shape s when s.Size.height > 100: return $"large shape with size {s.Size} at position {s.Position}"; case Ellipse e: return $"Ellipse with size {e.Size} at position {e.Position}"; case Rectangle r: return $"Rectangle with size {r.Size} at position {r.Position}"; default: return "another shape"; } }
  • 49. switch Expression static string M2(Shape shape) => shape switch { Shape s when s.Size.height > 100 => $"large shape with size {s.Size} at position {s.Position}", Ellipse e => $"Ellipse with size {e.Size} at position {e.Position}", Rectangle r => $"Rectangle with size {r.Size} at position {r.Position}", _ => "another shape" } };
  • 50. Recursive, Property, and Discard Patterns static string M3(Shape shape) => shape switch { CombinedShape (var shape1, var (pos, _)) => $"combined shape - shape1: {shape1.Name}, pos of shape2: {pos}", { Size: (200, 200), Position: var pos } => $"shape with size 200x200 at position {pos.x}:{pos.y}", Ellipse (var pos, var size) => $"Ellipse with size {size} at position {pos}", Rectangle (_, var size) => $"Rectangle with size {size}", _ => "another shape" };
  • 51. Null References Most common .NET Exception NullReferenceException Billion Dollar Mistake 1965 in Algol by Tony Hoare "Billion Dollar Mistake"
  • 52. Null Conditional Operator (C# 6) • Reduce Null-Checks int? length = customers?.Length; Customer first = customers?[0]; int? count = customers?[0]?.Orders?.Count(); public void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  • 53. Coalescing Operator (C# 5) • Default values for null int length = customers?.Length ?? 0; public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;
  • 54. Nullable Reference Types • Hilft finden von Bugs, aber keine Garantie! • Flow analysis - tracks nullable reference variables • Breaks existing code (opt-in) • Nullability implemented with metadata (ignored by downlevel compilers) • string, T non-nullable • string?, T? nullable
  • 55. Declare Nullable Reference Types • Default to non-nullable • ? to make reference type nullable class Book { public Book(string title, string? isbn = null) { Title = title; Isbn = isbn; } public string Title; // not null public string? Isbn; // may be null }
  • 56. Using nullable reference type void M1(string? ns) { Console.WriteLine(ns.Length); // compiler warning void M2(string? ns) { if (ns == null) throw new ArgumentNullException(nameof(ns)); Console.WriteLine(ns.Length); // ok, not null ns = null; Console.WriteLine(ns.Length); // compiler warning void M3(string? ns) { if (ns != null) { Console.WriteLine(ns.Length); // ok
  • 57. Using non-nullable reference type void M1(string ns) { Console.WriteLine(ns.Length); // ok void M2(Book b) { b.Title = null; // warning string isbn = b.Isbn; // warning – may be null string title = b.Title; // ok
  • 58. Compatibility • Enable this in your own speed // Enable assembly-level [module: NonNullTypes] [NonNullTypes(false)] public class Foo { }
  • 59. Summary C# 8 Nullable Reference Types Indexes and Ranges Async Streams Magic
  • 61. What's next – Try it out! • https://github.com/dotnet/csharplang/wiki/Nullable- Reference-Types-Preview • Visual Studio 2017 15.5-15.8 (funktioniert nicht mit 15.8.4, 15.8.5) Nullable Reference Types • https://github.com/dotnet/csharplang/wiki/vNext- Preview • Visual Studio 2017 15.5-15.7 Patterns und Ranges • https://github.com/dotnet/roslyn Andere Features
  • 62. More Information • https://github.com/ProfessionalCSharp • https://csharp.christiannagel.com • https://www.cninnovation.com • Training & Coaching
  • 63.