SlideShare a Scribd company logo
1 of 42
Download to read offline
C# 8 in Libraries and
Applications
Christian Nagel
https://csharp.christiannagel.com
Topics
NEW C# 8 FEATURES HOW TO USE C# 8 IN
LIBRARIES AND
APPLICATIONS
GUIDELINES
Christian Nagel
• Training
• Coaching
• Consulting
• Development
• Microsoft MVP
• www.cninnovation.com
• csharp.christiannagel.com
• github.com/cninnovation
How to use C# 8
How to use C# 8
• By default enabled with
.NET Core 3.0
• Enable with other projects
• <LangVersion>8.0</LangVersion>
• <Nullable>enable</Nullable>
• Directory.Build.Props
Features based on
Frameworks/Runtimes
• Syntax Sugar Features mit allen Frameworks
• Manche Features brauchen Klassen &
Interfaces
• Ranges, async streams
• Runtime Updates Required
• .NET Standard 2.1
• Default Interface Members
Default Interface Members
Default
Interface
Members -
Overview
• Interfaces mit Implementierung
• Modifiers: private, protected, internal, public,
virtual, abstract, override, sealed, static, extern
Default Interface Methods
Ändern von Interfaces
ohne Breaking
Changes
1
Traits –
Wiederverwendbarkeit
von Methoden in
unabhängigen Klassen
2
Basiert auf Java's
Default Methods
3
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);
}
Demo
• Default Interface Members
• Interface mit breaking change
• Interface mit non-breaking change
• Traits
Tipps
Ist die erste Version eines Interfaces
komplett?
Erweiterungen sind jetzt möglich!
Alternative zu Extension Methoden
Runtime-Erweiterungen!
Indices and Ranges
Indexes and Ranges
Index und
Range &
Types &
Extensions
New
Operators
• ^ Hat Operator
• .. Range
Operator
Hat Operator
int[] arr = { 1, 2, 3 };
int lastItem = arr[^1];
Range
string text1 = "the quick brown fox jumped over the lazy dogs";
string quick = text1[4..9];
string dog = text1[^4..^1];
string brownfoxjumpedandmore = text1[10..];
string thequick = text1[..8];
string text2 = text1[..];
Demo
• Ranges and Indices
• Access Slice of Span<T>
• Access String
• Range, Index Types
• Custom Collections
Implicit
Support
Index
•countable (Length, Count)
•instance indexer with int
Range
•countable
•Slice method with two int
Nullable Reference Types
Null References
Most common .NET Exception
NullReferenceException
Billion Dollar Mistake
1965 in Algol by Tony Hoare "Billion Dollar Mistake"
Null Conditional Operator (C# 6)
• Null checks made easier
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;
Reference
Types are not
Nullable
• #nullable enable/disable/restore
• annotated with ? – nullable reference type
• string?
• Null-forgiving operator
• !
• Null-coalescing assignment
• numbers ??= new List<string>();
Nullable Reference Types
• Dokumentation: null oder nicht null
• 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
Demo
• Nullable Reference Types
• Enable nullability
• Add annotations
• Solving issues
• Current issues
Guidelines
• Library authors – Nullable adoption phase before
.NET 5
• App developers – nullability on your own pace
• Annotate new APIs
• Do not remove argument validation
• Parameter is non-nullable if parameters are
checked (ArgumentNullException)
• Parameter is nullable if documented to accept null
• Prefer nullable over non-nullable with
disagreements
Async Streams
Async
Streams
bis jetzt: 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
{
ValueTask DisposeAsync();
}
public interface IAsyncEnumerable<out T>
{
IAsyncEnumerator<T> GetAsyncEnumerator();
}
public interface IAsyncEnumerator<out T> :
IAsyncDisposable
{
ValueTask<bool> MoveNextAsync();
T Current { get; }
}
Using Async Streams
• await foreach
IAsyncEnumerator<T> enumerator =
enumerable.GetAsyncEnumerator();
try
{
while (await enumerator.MoveNextAsync())
{
Use(enumerator.Current);
}
}
finally
{
await enumerator.DisposeAsync();
}
await foreach (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");
}
}
Demo
• Async Streams & SignalR
• Streaming from the Server to the
Client
• Streaming from the Client to the
Server
• C# 8 Async Streams
More Features…
using declaration
public void Method(IEnumerable<string> lines)
{
using var file = new StreamWriter("sample.txt");
foreach (var line in lines)
{
file.WriteLine(line);
}
}
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"
};
Demo
• Switch expressions with tuples
• Pattern matching
Summary
Avoid Errors
Better Productivity
Better Performance
Questions?
For action
• Annotate libraries with nullability
• Use new C# 8 features
• https://csharp.christiannagel.com
• https://github.com/cninnovation
• https://github.com/ProfessionalCSharp
Thank you!

More Related Content

What's hot

What's hot (20)

Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
 
Domain Specific Development using T4
Domain Specific Development using T4Domain Specific Development using T4
Domain Specific Development using T4
 
UPenn on Rails intro
UPenn on Rails introUPenn on Rails intro
UPenn on Rails intro
 
Reflection in Pharo5
Reflection in Pharo5Reflection in Pharo5
Reflection in Pharo5
 
APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...
APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...
APIdays Paris 2018 - Building scalable, type-safe GraphQL servers from scratc...
 
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
 
Dynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection PromisesDynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection Promises
 
A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5
 
Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014
 
Asp.Net 3.5 Part 2
Asp.Net 3.5 Part 2Asp.Net 3.5 Part 2
Asp.Net 3.5 Part 2
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
 
Translate word press to your language
Translate word press to your languageTranslate word press to your language
Translate word press to your language
 
Cassandra Summit 2015 - Building a multi-tenant API PaaS with DataStax Enterp...
Cassandra Summit 2015 - Building a multi-tenant API PaaS with DataStax Enterp...Cassandra Summit 2015 - Building a multi-tenant API PaaS with DataStax Enterp...
Cassandra Summit 2015 - Building a multi-tenant API PaaS with DataStax Enterp...
 
LINEデリマでのElasticsearchの運用と監視の話
LINEデリマでのElasticsearchの運用と監視の話LINEデリマでのElasticsearchの運用と監視の話
LINEデリマでのElasticsearchの運用と監視の話
 
Angular4 kickstart
Angular4 kickstartAngular4 kickstart
Angular4 kickstart
 
Roslyn
RoslynRoslyn
Roslyn
 
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
 
PHP7.1 New Features & Performance
PHP7.1 New Features & PerformancePHP7.1 New Features & Performance
PHP7.1 New Features & Performance
 
Writing High Peformance C# 7 Code
Writing High Peformance C# 7 CodeWriting High Peformance C# 7 Code
Writing High Peformance C# 7 Code
 

Similar to C# 8 in Libraries and Applications

Irving iOS Jumpstart Meetup - Objective-C Session 1a
Irving iOS Jumpstart Meetup - Objective-C Session 1aIrving iOS Jumpstart Meetup - Objective-C Session 1a
Irving iOS Jumpstart Meetup - Objective-C Session 1a
irving-ios-jumpstart
 

Similar to C# 8 in Libraries and Applications (20)

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
 
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)
 
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8
 
C# - What's next
C# - What's nextC# - What's next
C# - What's next
 
Java 8
Java 8Java 8
Java 8
 
What's new in c# 8.0
What's new in c# 8.0What's new in c# 8.0
What's new in c# 8.0
 
APEX 5 IR: Guts & Performance
APEX 5 IR:  Guts & PerformanceAPEX 5 IR:  Guts & Performance
APEX 5 IR: Guts & Performance
 
APEX 5 IR Guts and Performance
APEX 5 IR Guts and PerformanceAPEX 5 IR Guts and Performance
APEX 5 IR Guts and Performance
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
C# - What's Next?
C# - What's Next?C# - What's Next?
C# - What's Next?
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ tool
 
APEX 5 Interactive Reports: Guts and PErformance
APEX 5 Interactive Reports: Guts and PErformanceAPEX 5 Interactive Reports: Guts and PErformance
APEX 5 Interactive Reports: Guts and PErformance
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
C
CC
C
 
Angular2
Angular2Angular2
Angular2
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
Bringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptxBringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptx
 
Irving iOS Jumpstart Meetup - Objective-C Session 1a
Irving iOS Jumpstart Meetup - Objective-C Session 1aIrving iOS Jumpstart Meetup - Objective-C Session 1a
Irving iOS Jumpstart Meetup - Objective-C Session 1a
 

More from Christian Nagel

More from Christian Nagel (10)

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
 
Gemeinsame View-Models mit XAML Technologien
Gemeinsame View-Models mit XAML TechnologienGemeinsame View-Models mit XAML Technologien
Gemeinsame View-Models mit XAML Technologien
 
Adaptive Cards - User Interfaces with JSON
Adaptive Cards - User Interfaces with JSONAdaptive Cards - User Interfaces with JSON
Adaptive Cards - User Interfaces with JSON
 
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
 
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

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+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
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
%+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...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 

C# 8 in Libraries and Applications

  • 1. C# 8 in Libraries and Applications Christian Nagel https://csharp.christiannagel.com
  • 2. Topics NEW C# 8 FEATURES HOW TO USE C# 8 IN LIBRARIES AND APPLICATIONS GUIDELINES
  • 3. Christian Nagel • Training • Coaching • Consulting • Development • Microsoft MVP • www.cninnovation.com • csharp.christiannagel.com • github.com/cninnovation
  • 4. How to use C# 8
  • 5. How to use C# 8 • By default enabled with .NET Core 3.0 • Enable with other projects • <LangVersion>8.0</LangVersion> • <Nullable>enable</Nullable> • Directory.Build.Props
  • 6. Features based on Frameworks/Runtimes • Syntax Sugar Features mit allen Frameworks • Manche Features brauchen Klassen & Interfaces • Ranges, async streams • Runtime Updates Required • .NET Standard 2.1 • Default Interface Members
  • 8. Default Interface Members - Overview • Interfaces mit Implementierung • Modifiers: private, protected, internal, public, virtual, abstract, override, sealed, static, extern
  • 9. Default Interface Methods Ändern von Interfaces ohne Breaking Changes 1 Traits – Wiederverwendbarkeit von Methoden in unabhängigen Klassen 2 Basiert auf Java's Default Methods 3
  • 10. 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); }
  • 11. Demo • Default Interface Members • Interface mit breaking change • Interface mit non-breaking change • Traits
  • 12. Tipps Ist die erste Version eines Interfaces komplett? Erweiterungen sind jetzt möglich! Alternative zu Extension Methoden Runtime-Erweiterungen!
  • 14. Indexes and Ranges Index und Range & Types & Extensions New Operators • ^ Hat Operator • .. Range Operator
  • 15. Hat Operator int[] arr = { 1, 2, 3 }; int lastItem = arr[^1];
  • 16. Range string text1 = "the quick brown fox jumped over the lazy dogs"; string quick = text1[4..9]; string dog = text1[^4..^1]; string brownfoxjumpedandmore = text1[10..]; string thequick = text1[..8]; string text2 = text1[..];
  • 17. Demo • Ranges and Indices • Access Slice of Span<T> • Access String • Range, Index Types • Custom Collections
  • 18. Implicit Support Index •countable (Length, Count) •instance indexer with int Range •countable •Slice method with two int
  • 20. Null References Most common .NET Exception NullReferenceException Billion Dollar Mistake 1965 in Algol by Tony Hoare "Billion Dollar Mistake"
  • 21. Null Conditional Operator (C# 6) • Null checks made easier 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));
  • 22. Coalescing Operator (C# 5) • Default values for null int length = customers?.Length ?? 0; public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;
  • 23. Reference Types are not Nullable • #nullable enable/disable/restore • annotated with ? – nullable reference type • string? • Null-forgiving operator • ! • Null-coalescing assignment • numbers ??= new List<string>();
  • 24. Nullable Reference Types • Dokumentation: null oder nicht null • 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
  • 25. Demo • Nullable Reference Types • Enable nullability • Add annotations • Solving issues • Current issues
  • 26. Guidelines • Library authors – Nullable adoption phase before .NET 5 • App developers – nullability on your own pace • Annotate new APIs • Do not remove argument validation • Parameter is non-nullable if parameters are checked (ArgumentNullException) • Parameter is nullable if documented to accept null • Prefer nullable over non-nullable with disagreements
  • 28. Async Streams bis jetzt: 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
  • 29. Async Streams • IAsyncDisposable • IAsyncEnumerable • IAsyncEnumerator public interface IAsyncDisposable { ValueTask DisposeAsync(); } public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(); } public interface IAsyncEnumerator<out T> : IAsyncDisposable { ValueTask<bool> MoveNextAsync(); T Current { get; } }
  • 30. Using Async Streams • await foreach IAsyncEnumerator<T> enumerator = enumerable.GetAsyncEnumerator(); try { while (await enumerator.MoveNextAsync()) { Use(enumerator.Current); } } finally { await enumerator.DisposeAsync(); } await foreach (var i in enumerable) { Use(i); }
  • 31. 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"); } }
  • 32. Demo • Async Streams & SignalR • Streaming from the Server to the Client • Streaming from the Client to the Server • C# 8 Async Streams
  • 34. using declaration public void Method(IEnumerable<string> lines) { using var file = new StreamWriter("sample.txt"); foreach (var line in lines) { file.WriteLine(line); } }
  • 35. 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" } };
  • 36. 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" };
  • 37. Demo • Switch expressions with tuples • Pattern matching
  • 40. For action • Annotate libraries with nullability • Use new C# 8 features • https://csharp.christiannagel.com • https://github.com/cninnovation • https://github.com/ProfessionalCSharp
  • 41.