SlideShare a Scribd company logo
C# 7.x What’s new and
What’s coming with C# 8
#THRIVEITCONF
C# STRATEGY
Continuous enhancements
Fulfill changing needs
Agenda
C#
Strategy
C#
Today
C#
Future
Christian Nagel
• Independent Consultant
• Training
• Coaching
• Coding
• Writing
csharp.christiannagel.com
www.cninnovation.com
@christiannagel
Microsoft MVP
Fast innovations
Spirit of C#
Goals with C# 7.1, 7.2, 7.3
• Reduce garbage collection
• No copy
• "Safe" Code
Efficient Code
• Additional possibilities
More Options
• "Say it shorter"
Less Code
C# 8
Magic
C# 7.X TODAY
C# 7.0
Tuples &
Deconstruction
Pattern
Matching
Expressions
everywhere
Reference
Semantics
Tuples
• Combine different types
• 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;
}
}
Reference Semantics
• return values by reference
• Span<T> Type
public ref int ReturnValueByReference(int[] data, int index)
{
ref int x = ref data[index]; // local ref
return ref x; // ref return
}
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
• Safe, efficient code
• More options
• Reduce code writing
C# 8
State
Proposal
Discussed/Decision in LDM
Prototype
Implementation in Progress
Implemented
State: Implemented
• Default literal deconstruction (not yet in VS 2019)
• Alternative interpolated verbatim strings (VS 2019 Preview 1 – [16.0pv1])
(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 (16.0pv1)
• Async streams (16.0pv1*)
• Ranges (16.0pv1)
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 (16.0pv1)
• 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
Chang interfaces without breaking changes
Traits – Reuse methods in independent types
Based on 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);
}
• private
• protected
• internal
• public
• virtual
• abstract
• override
• sealed
• static
• extern
Default Interface Methods
Allowed Modifiers
Default Interface Methods
Multiple Inheritance with 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 returns a result
• Async Streams  stream of results
• Asynchronous 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> :
IAsyncDiposable
{
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");
}
}
Async Streams Open Questions
• LINQ
• ~600 new methods would be necessary
• Interactive Extensions (Ix) implements most
•  Support Community to extend Ix
• Integration with IObservable<T>
• Integration using libraries
Patterns Extended
• Always match
Discard Pattern
• Match property values
Property Pattern
• Match inner properties
Recursive Pattern
• Modern 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"
};
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[..];
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;
• Helps finding bugs – no 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
Nullable Reference Types
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?
THANK YOU!
https://csharp.christiannagel.com

More Related Content

What's hot

Java Generics
Java GenericsJava Generics
Java Generics
Carol McDonald
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
Pierre de Lacaze
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
Sumant Tambe
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
heinrich.wendel
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
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
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
knutmork
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
Java Generics
Java GenericsJava Generics
Java Generics
Zülfikar Karakaya
 
Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspective
Norman Richards
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
C++11
C++11C++11
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
Knoldus Inc.
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
 

What's hot (20)

Java Generics
Java GenericsJava Generics
Java Generics
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
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
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspective
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
C++11
C++11C++11
C++11
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
 

Similar to C# 7.x What's new and what's coming with C# 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)
Christian Nagel
 
C# 8 in Libraries and Applications
C# 8 in Libraries and ApplicationsC# 8 in Libraries and Applications
C# 8 in Libraries and Applications
Christian Nagel
 
C# - What's Next?
C# - What's Next?C# - What's Next?
C# - What's Next?
Christian Nagel
 
C++ process new
C++ process newC++ process new
C++ process new
敬倫 林
 
C
CC
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?
Kevin Pilch
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
shivam460694
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
Anand Kumar Rajana
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
kinan keshkeh
 
Introduction to c#
Introduction to c#Introduction to c#
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...
Muhammad Ulhaque
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
Rohit Rao
 
Modern C++
Modern C++Modern C++
Modern C++
Michael Clark
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
Snehal Harawande
 
Session 4
Session 4Session 4
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in CppEffective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
CodeOps Technologies LLP
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
kinan keshkeh
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 
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"
Yulia Tsisyk
 

Similar to C# 7.x What's new and what's coming with C# 8 (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)
 
C# 8 in Libraries and Applications
C# 8 in Libraries and ApplicationsC# 8 in Libraries and Applications
C# 8 in Libraries and Applications
 
C# - What's Next?
C# - What's Next?C# - What's Next?
C# - What's Next?
 
C++ process new
C++ process newC++ process new
C++ process new
 
C
CC
C
 
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?
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
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...
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
Modern C++
Modern C++Modern C++
Modern C++
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
 
Session 4
Session 4Session 4
Session 4
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in CppEffective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
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"
 

More from Christian Nagel

Async streams
Async streamsAsync streams
Async streams
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 applications
Christian 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 2021
Christian 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
 
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
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 Advanced
Christian Nagel
 
Gemeinsame View-Models mit XAML Technologien
Gemeinsame View-Models mit XAML TechnologienGemeinsame View-Models mit XAML Technologien
Gemeinsame View-Models mit XAML Technologien
Christian Nagel
 
C# 8 and .NET Core 3
C# 8 and .NET Core 3C# 8 and .NET Core 3
C# 8 and .NET Core 3
Christian 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 JSON
Christian 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 2019
Christian 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 WPF
Christian 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 Core
Christian 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 Platform
Christian 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 Developers
Christian 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 geplant
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

The Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdfThe Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdf
mohitd6
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.
KrishnaveniMohan1
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
Optimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptxOptimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptx
WebConnect Pvt Ltd
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 

Recently uploaded (20)

The Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdfThe Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdf
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
Optimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptxOptimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptx
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 

C# 7.x What's new and what's coming with C# 8

  • 1. C# 7.x What’s new and What’s coming with C# 8 #THRIVEITCONF
  • 3.
  • 6. Christian Nagel • Independent Consultant • Training • Coaching • Coding • Writing csharp.christiannagel.com www.cninnovation.com @christiannagel Microsoft MVP
  • 7.
  • 9.
  • 10.
  • 11. Goals with C# 7.1, 7.2, 7.3 • Reduce garbage collection • No copy • "Safe" Code Efficient Code • Additional possibilities More Options • "Say it shorter" Less Code
  • 15. Tuples • Combine different types • 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. Reference Semantics • return values by reference • Span<T> Type public ref int ReturnValueByReference(int[] data, int index) { ref int x = ref data[index]; // local ref return ref x; // ref return }
  • 19. 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;
  • 20. 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; }
  • 21. 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 };
  • 22. C# 7 Point Releases • Safe, efficient code • More options • Reduce code writing
  • 23. C# 8
  • 25. State: Implemented • Default literal deconstruction (not yet in VS 2019) • Alternative interpolated verbatim strings (VS 2019 Preview 1 – [16.0pv1]) (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
  • 26. State: In Progress • Generic attributes • Relax ordering ref and partial modifiers • Null coalescing assignment (16.0pv1) • Async streams (16.0pv1*) • Ranges (16.0pv1) 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
  • 27. State: Prototype • Caller expression attribute • Target-typed new • Pattern-based using • Default interface methods • Nullable reference type (16.0pv1) • 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");
  • 28. Default Interface Methods Chang interfaces without breaking changes Traits – Reuse methods in independent types Based on Java's default methods
  • 29. 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); }
  • 30. • private • protected • internal • public • virtual • abstract • override • sealed • static • extern Default Interface Methods Allowed Modifiers
  • 31. Default Interface Methods Multiple Inheritance with 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(); }
  • 32. 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(); }
  • 33. Default Interface Methods Re-Abstract interface I0 { void M(); } interface I2 : I0 { override void M(); } interface I1 : I0 { override void M() => Console.WriteLine("I1"); }
  • 34. Async Streams • async/await returns a result • Async Streams  stream of results • Asynchronous sources controlled by the consumer • Alternative to System.Reactive
  • 35. Async Streams • IAsyncDisposable • IAsyncEnumerable • IAsyncEnumerator public interface IAsyncDisposable { ValueTask DisposeAsync(); } public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(); } public interface IAsyncEnumerator<out T> : IAsyncDiposable { ValueTask<bool> MoveNextAsync(); T Current { get; } }
  • 36. 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); }
  • 37. 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"); } }
  • 38. Async Streams Open Questions • LINQ • ~600 new methods would be necessary • Interactive Extensions (Ix) implements most •  Support Community to extend Ix • Integration with IObservable<T> • Integration using libraries
  • 39. Patterns Extended • Always match Discard Pattern • Match property values Property Pattern • Match inner properties Recursive Pattern • Modern switch syntax switch Expression
  • 40. 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"; } }
  • 41. 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" } };
  • 42. 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" };
  • 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. Null References Most common .NET Exception NullReferenceException Billion Dollar Mistake 1965 in Algol by Tony Hoare "Billion Dollar Mistake"
  • 47. 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));
  • 48. Coalescing Operator (C# 5) • Default values for null int length = customers?.Length ?? 0; public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;
  • 49. • Helps finding bugs – no 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 Nullable Reference Types
  • 50. 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 }
  • 51. 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
  • 52. 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
  • 53. Compatibility • Enable this in your own speed // Enable assembly-level [module: NonNullTypes] [NonNullTypes(false)] public class Foo { }
  • 54. Summary C# 8 Nullable Reference Types Indexes and Ranges Async Streams Magic