SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Downloaden Sie, um offline zu lesen
C# 8 in Libraries and
Applications
Christian Nagel
https://csharp.christiannagel.com
Topics
New C# 8 Features
Moving from existing code
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 and .NET Standard 2.1
• Enable with other projects: <LangVersion>
• Directory.Build.Props File
Features based on
Frameworks/Runtimes
• Syntax sugar features with all frameworks
• Some features need specific classes &
interfaces
• Ranges, async streams
• Runtime updates required
• .NET Standard 2.1
• Default Interface Members
Nullable Reference Types
Null References
• Billion Doller Mistake
• 1965 in Algol by Sir Tony Hoare
• Most common .NET Exception
• NullReferenceException
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 (C# 8)
• #nullable enable/disable/restore
• annotated with ? – nullable reference type
• string?
• Null-forgiving operator
• !
• Null-coalescing assignment
• numbers ??= new List<string>();
Features - Nullable Reference Types
• Documentation: null or not null
• Helps finding bugs, not a guarantee!
• 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 up to
.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
Default Interface Members
Default Interface Members - Overview
• Interfaces with implementation
• Modifiers: private, protected,
internal, public, virtual, abstract,
override, sealed, static, extern
Default Interface Methods
Changing of
interfaces without
breaking changes
1
Traits – Reuse
implementations in
independent types
2
Based on 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);
}
Tipps
Is the first version of the interface
complete?
Additions are now possible!
Alternative to extension methods
Runtime extensions needed!
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
• countable (Length, Count)
• instance indexer with int
Index
• countable
• Slice method with two int
Range
Async Streams
Async
Streams
Async before: async/await returns one
result
Async streams extends async/await with
a stream of results
Async sources controlled by the
consumer
Alternative to 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
• Switch with 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/christiannagel
https://github.com/ProfessionalCSharp
Thank you!

Weitere ähnliche Inhalte

Was ist angesagt?

Testing sync engine
Testing sync engineTesting sync engine
Testing sync engineIlya Puchka
 
Advanced debugging
Advanced debuggingAdvanced debugging
Advanced debuggingAli Akhtar
 
Tech Days 2015: A quick tour of Ada 2012
Tech Days 2015: A quick tour of Ada 2012Tech Days 2015: A quick tour of Ada 2012
Tech Days 2015: A quick tour of Ada 2012AdaCore
 
Automation is Easy! (python version)
Automation is Easy! (python version)Automation is Easy! (python version)
Automation is Easy! (python version)Iakiv Kramarenko
 
Augmenting Field Data for Testing Systems Subject to Incremental Requirements...
Augmenting Field Data for Testing Systems Subject to Incremental Requirements...Augmenting Field Data for Testing Systems Subject to Incremental Requirements...
Augmenting Field Data for Testing Systems Subject to Incremental Requirements...Lionel Briand
 
Pure functions
Pure functionsPure functions
Pure functionsPer Arneng
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform ResearchVasil Remeniuk
 
Systematic Evaluation of the Unsoundness of Call Graph Algorithms for Java
Systematic Evaluation of the Unsoundness of Call Graph Algorithms for JavaSystematic Evaluation of the Unsoundness of Call Graph Algorithms for Java
Systematic Evaluation of the Unsoundness of Call Graph Algorithms for JavaMichael Reif
 
TMPA-2015: Towards a Usable Defect Prediction Tool: Crossbreeding Machine Lea...
TMPA-2015: Towards a Usable Defect Prediction Tool: Crossbreeding Machine Lea...TMPA-2015: Towards a Usable Defect Prediction Tool: Crossbreeding Machine Lea...
TMPA-2015: Towards a Usable Defect Prediction Tool: Crossbreeding Machine Lea...Iosif Itkin
 
Automated Software Testing
Automated Software TestingAutomated Software Testing
Automated Software Testingarild2
 
Aspect Oriented Programming: Hidden Toolkit That You Already Have
Aspect Oriented Programming: Hidden Toolkit That You Already HaveAspect Oriented Programming: Hidden Toolkit That You Already Have
Aspect Oriented Programming: Hidden Toolkit That You Already HaveSalesforce Engineering
 
Application of the Actor Model to Large Scale NDE Data Analysis
Application of the Actor Model to Large Scale NDE Data AnalysisApplication of the Actor Model to Large Scale NDE Data Analysis
Application of the Actor Model to Large Scale NDE Data AnalysisChrisCoughlin9
 
Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Brooklyn Zelenka
 
Introduction to PSPICE
Introduction to PSPICEIntroduction to PSPICE
Introduction to PSPICEsyella
 
Ebay legacy-code-retreat
Ebay legacy-code-retreatEbay legacy-code-retreat
Ebay legacy-code-retreatKonrad Malawski
 
Scaffolding with JMock
Scaffolding with JMockScaffolding with JMock
Scaffolding with JMockValerio Maggio
 
Generating unit tests based on user logs
Generating unit tests based on user logsGenerating unit tests based on user logs
Generating unit tests based on user logsRick Wicker
 
Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)Trisha Gee
 

Was ist angesagt? (20)

Testing sync engine
Testing sync engineTesting sync engine
Testing sync engine
 
Advanced debugging
Advanced debuggingAdvanced debugging
Advanced debugging
 
Tech Days 2015: A quick tour of Ada 2012
Tech Days 2015: A quick tour of Ada 2012Tech Days 2015: A quick tour of Ada 2012
Tech Days 2015: A quick tour of Ada 2012
 
Automation is Easy! (python version)
Automation is Easy! (python version)Automation is Easy! (python version)
Automation is Easy! (python version)
 
Augmenting Field Data for Testing Systems Subject to Incremental Requirements...
Augmenting Field Data for Testing Systems Subject to Incremental Requirements...Augmenting Field Data for Testing Systems Subject to Incremental Requirements...
Augmenting Field Data for Testing Systems Subject to Incremental Requirements...
 
Qtp - Introduction to automation basics
Qtp -  Introduction to automation basicsQtp -  Introduction to automation basics
Qtp - Introduction to automation basics
 
Pure functions
Pure functionsPure functions
Pure functions
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform Research
 
Systematic Evaluation of the Unsoundness of Call Graph Algorithms for Java
Systematic Evaluation of the Unsoundness of Call Graph Algorithms for JavaSystematic Evaluation of the Unsoundness of Call Graph Algorithms for Java
Systematic Evaluation of the Unsoundness of Call Graph Algorithms for Java
 
TMPA-2015: Towards a Usable Defect Prediction Tool: Crossbreeding Machine Lea...
TMPA-2015: Towards a Usable Defect Prediction Tool: Crossbreeding Machine Lea...TMPA-2015: Towards a Usable Defect Prediction Tool: Crossbreeding Machine Lea...
TMPA-2015: Towards a Usable Defect Prediction Tool: Crossbreeding Machine Lea...
 
Automated Software Testing
Automated Software TestingAutomated Software Testing
Automated Software Testing
 
Aspect Oriented Programming: Hidden Toolkit That You Already Have
Aspect Oriented Programming: Hidden Toolkit That You Already HaveAspect Oriented Programming: Hidden Toolkit That You Already Have
Aspect Oriented Programming: Hidden Toolkit That You Already Have
 
Application of the Actor Model to Large Scale NDE Data Analysis
Application of the Actor Model to Large Scale NDE Data AnalysisApplication of the Actor Model to Large Scale NDE Data Analysis
Application of the Actor Model to Large Scale NDE Data Analysis
 
Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)
 
Introduction to PSPICE
Introduction to PSPICEIntroduction to PSPICE
Introduction to PSPICE
 
Ebay legacy-code-retreat
Ebay legacy-code-retreatEbay legacy-code-retreat
Ebay legacy-code-retreat
 
Introduction to Python Programming
Introduction to Python Programming Introduction to Python Programming
Introduction to Python Programming
 
Scaffolding with JMock
Scaffolding with JMockScaffolding with JMock
Scaffolding with JMock
 
Generating unit tests based on user logs
Generating unit tests based on user logsGenerating unit tests based on user logs
Generating unit tests based on user logs
 
Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)
 

Ähnlich wie C# 8 in Libraries and Applications - BASTA! Frankfurt 2020

C# 8 in Libraries and Applications
C# 8 in Libraries and ApplicationsC# 8 in Libraries and Applications
C# 8 in Libraries and ApplicationsChristian Nagel
 
An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...
An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...
An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...Jean Vanderdonckt
 
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.0Moaid Hathot
 
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)Christian Nagel
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
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# 8Christian Nagel
 
Practices and Tools for Building Better APIs
Practices and Tools for Building Better APIsPractices and Tools for Building Better APIs
Practices and Tools for Building Better APIsPeter Hendriks
 
TMPA-2015: The Application of Parameterized Hierarchy Templates for Automated...
TMPA-2015: The Application of Parameterized Hierarchy Templates for Automated...TMPA-2015: The Application of Parameterized Hierarchy Templates for Automated...
TMPA-2015: The Application of Parameterized Hierarchy Templates for Automated...Iosif Itkin
 
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Raffi Khatchadourian
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6Andy Butland
 
Workflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic AppsWorkflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic AppsJosh Lane
 
Structured Functional Automated Web Service Testing
Structured Functional Automated Web Service TestingStructured Functional Automated Web Service Testing
Structured Functional Automated Web Service Testingrdekleijn
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application TestingTroy Miles
 
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 PErformanceKaren Cannell
 

Ähnlich wie C# 8 in Libraries and Applications - BASTA! Frankfurt 2020 (20)

C# 8 in Libraries and Applications
C# 8 in Libraries and ApplicationsC# 8 in Libraries and Applications
C# 8 in Libraries and Applications
 
Angular2
Angular2Angular2
Angular2
 
An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...
An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...
An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...
 
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
 
Java 8
Java 8Java 8
Java 8
 
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)
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
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
 
CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019
 
Practices and Tools for Building Better APIs
Practices and Tools for Building Better APIsPractices and Tools for Building Better APIs
Practices and Tools for Building Better APIs
 
TMPA-2015: The Application of Parameterized Hierarchy Templates for Automated...
TMPA-2015: The Application of Parameterized Hierarchy Templates for Automated...TMPA-2015: The Application of Parameterized Hierarchy Templates for Automated...
TMPA-2015: The Application of Parameterized Hierarchy Templates for Automated...
 
Angular 2
Angular 2Angular 2
Angular 2
 
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
C-Sharp 6.0 ver2
C-Sharp 6.0 ver2C-Sharp 6.0 ver2
C-Sharp 6.0 ver2
 
Workflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic AppsWorkflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic Apps
 
Structured Functional Automated Web Service Testing
Structured Functional Automated Web Service TestingStructured Functional Automated Web Service Testing
Structured Functional Automated Web Service Testing
 
C#: Past, Present and Future
C#: Past, Present and FutureC#: Past, Present and Future
C#: Past, Present and Future
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application Testing
 
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
 

Mehr von Christian Nagel

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?Christian Nagel
 
Azure App Configuration with .NET applications
Azure App Configuration with .NET applicationsAzure App Configuration with .NET applications
Azure App Configuration with .NET applicationsChristian Nagel
 
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 2021Christian Nagel
 
.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...Christian Nagel
 
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 AdvancedChristian Nagel
 
Gemeinsame View-Models mit XAML Technologien
Gemeinsame View-Models mit XAML TechnologienGemeinsame View-Models mit XAML Technologien
Gemeinsame View-Models mit XAML TechnologienChristian Nagel
 
.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?Christian Nagel
 
Adaptive Cards - User Interfaces with JSON
Adaptive Cards - User Interfaces with JSONAdaptive Cards - User Interfaces with JSON
Adaptive Cards - User Interfaces with JSONChristian Nagel
 
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 2019Christian Nagel
 
Blazor - The New Silverlight?
Blazor - The New Silverlight?Blazor - The New Silverlight?
Blazor - The New Silverlight?Christian Nagel
 
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 WPFChristian Nagel
 
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 CoreChristian Nagel
 
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 PlatformChristian Nagel
 
Blazor - The New Silverlight?
Blazor - The New Silverlight?Blazor - The New Silverlight?
Blazor - The New Silverlight?Christian Nagel
 
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 DevelopersChristian Nagel
 
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 geplantChristian Nagel
 

Mehr von Christian Nagel (20)

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...
 
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
 
C# - What's next
C# - What's nextC# - What's next
C# - What's next
 
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
 
C# - What's Next?
C# - What's Next?C# - What's Next?
C# - What's Next?
 

Kürzlich hochgeladen

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 

Kürzlich hochgeladen (20)

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

C# 8 in Libraries and Applications - BASTA! Frankfurt 2020

  • 1. C# 8 in Libraries and Applications Christian Nagel https://csharp.christiannagel.com
  • 2. Topics New C# 8 Features Moving from existing code 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 and .NET Standard 2.1 • Enable with other projects: <LangVersion> • Directory.Build.Props File
  • 6. Features based on Frameworks/Runtimes • Syntax sugar features with all frameworks • Some features need specific classes & interfaces • Ranges, async streams • Runtime updates required • .NET Standard 2.1 • Default Interface Members
  • 8. Null References • Billion Doller Mistake • 1965 in Algol by Sir Tony Hoare • Most common .NET Exception • NullReferenceException
  • 9. 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));
  • 10. Coalescing Operator (C# 5) • Default values for null int length = customers?.Length ?? 0; public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;
  • 11. Reference Types are not Nullable (C# 8) • #nullable enable/disable/restore • annotated with ? – nullable reference type • string? • Null-forgiving operator • ! • Null-coalescing assignment • numbers ??= new List<string>();
  • 12. Features - Nullable Reference Types • Documentation: null or not null • Helps finding bugs, not a guarantee! • 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
  • 13. Demo • Nullable Reference Types • Enable nullability • Add annotations • Solving issues • Current issues
  • 14. Guidelines • Library authors – Nullable adoption phase up to .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
  • 16. Default Interface Members - Overview • Interfaces with implementation • Modifiers: private, protected, internal, public, virtual, abstract, override, sealed, static, extern
  • 17. Default Interface Methods Changing of interfaces without breaking changes 1 Traits – Reuse implementations in independent types 2 Based on Java's Default Methods 3
  • 18. 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); }
  • 19. Tipps Is the first version of the interface complete? Additions are now possible! Alternative to extension methods Runtime extensions needed!
  • 21. Indexes and Ranges Index und Range & Types & Extensions New Operators • ^ Hat Operator • .. Range Operator
  • 22. Hat Operator int[] arr = { 1, 2, 3 }; int lastItem = arr[^1];
  • 23. 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[..];
  • 24. Demo • Ranges and Indices • Access Slice of Span<T> • Access String • Range, Index Types • Custom Collections
  • 25. Implicit Support • countable (Length, Count) • instance indexer with int Index • countable • Slice method with two int Range
  • 27. Async Streams Async before: async/await returns one result Async streams extends async/await with a stream of results Async sources controlled by the consumer Alternative to System.Reactive
  • 28. 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; } }
  • 29. 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); }
  • 30. 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"); } }
  • 31. Demo • Async Streams & SignalR • Streaming from the Server to the Client • Streaming from the Client to the Server • C# 8 Async Streams
  • 33. using declaration public void Method(IEnumerable<string> lines) { using var file = new StreamWriter("sample.txt"); foreach (var line in lines) { file.WriteLine(line); } }
  • 34. 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" } };
  • 35. 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" };
  • 36. Demo • Switch expressions with tuples • Switch with pattern matching
  • 39. For action Annotate libraries with nullability Use new C# 8 features https://csharp.christiannagel.com https://github.com/christiannagel https://github.com/ProfessionalCSharp
  • 40.