SlideShare a Scribd company logo
The Little Wonders of C# 6
James Michael Hare
Microsoft Visual C# MVP
4/27/2015
http://www.blackrabbitcoder.net/
@BlkRabbitCoder
 The CTP for VS2015 is available for download
 Includes the CTP for C# 6
 Several new language features
 No earth-shaking changes
 Still compatible with .NET 4.5
 Syntactical sugar to help reduce boiler-plate code
 Helps improve code readability and maintainability
Visual Studio 2015 is Upon Us!
 The nameof() operator
 Auto-property initialization
 Indexed initializer lists
 The using static directive
 Method and property expressions
 String interpolation
 Enhanced exception filtering
 The null conditional operator (?.)
New C# 6 Features
 Sometimes we want the name of an identifier as a string
The nameof() Operator
 We can hard-code, but if we rename the variable, we
have to remember to update the string:
The nameof() Operator (cont)
 Now, you can get a string representation of an
identifier with nameof():
The nameof() Operator (cont)
 Before, if you wanted to default an auto-property to a
non-default value, there wasn’t a simple way.
 Either:
 Create a backing field with initializer, then wrap in
property
 Or create an auto-property and then assign a value in
the constructor
 This should really be a simple, one-step process.
Auto-Property Initialization
 Now instead of this:
Auto-Property Initialization (cont)
 Or this…:
Auto-Property Initialization (cont)
 We can now do this!
 Reduces several lines of boiler-plating.
Auto-Property Initialization (cont)
 In addition, you can use it even if the property has no
setter (i.e. a truly read-only property):
Auto-Property Initialization (cont)
 Initializer lists now allow you to use indexers if the
container supports them.
 For example, you used to have to initialize a
dictionary like this:
Indexed Initialization Lists
 But now you can use the indexer syntax instead:
 The syntax is much cleaner and clearly identifies
which string is the key and which is the value.
Indexed Initialization Lists (cont)
 Warning: just because a container supports indexing doesn’t
mean initializing with it will always be logically sound…
 For example:
 What’s wrong with this?
Indexed Initialization Lists (cont)
 It is legal and compiles with no errors.
 However, you are attempting to set elements that are
beyond the list size, which List<T> doesn’t allow.
 This is the same as doing this:
Indexed Initialization Lists (cont)
 So remember, it’s just syntactical sugar, it won’t stop
you from performing a run-time illegal action.
 To make that example work, you’d have to do
something like:
Indexed Initialization Lists (cont)
 There are many static methods where the enclosing
class mainly acts as an organization point (e.g. Math).
 Sometimes, these class names give context to the
static member being called.
 Other times, they become repetitive clutter.
 The using static declaration allows you to import the
static members of a type into your namespace.
 Also allows you to limit extension methods imported.
The using static Directive
 Consider the following:
 A lot of these class names we can assume from
context or are just organizational clutter.
The using static Directive (cont)
 If our program is a console app, we can probably
assume the Console.
 Similarly, the Math and Enumerable classes don’t add
much. We already know what Pow() and Range() do.
 Now, we can import the static members of these
types with using static:
The using static Directive (cont)
 This would simplify our code to be:
 We’ve removed a lot of redundant code without
obscuring the clarity.
The using static Directive (cont)
 It’s not just for classes, you can import the static
members of structs or enums.
 For example, doing this:
 Would allow us to do this:
The using static Directive (cont)
 Warning: just because you can do this doesn’t mean
you always should.
 Consider if you ran across this code:
 There’s no context, so what the heck are we creating?
 Here, the type would have given meaningful context:
The using static Directive (cont)
 Sometimes, we have properties or methods that are
so simple, the body is mostly boilerplate
Method and Property Expressions
 You can now simplify with lambda expression syntax:
 Handy for simple get-only properties, reduces the
boilerplate around the get { } syntax.
 Somewhat reduces syntax burden on methods.
Method and Property Expressions
(cont)
 Consider building a string in a single statement with
multiple components.
 Typically we either use concatenation:
 Or string formatting:
String Interpolation
 The problem with concatenation is that it breaks up
the flow of the string you are building and makes it
harder to envision the result.
 Formatting helps solve this, but it removes the actual
values from the string and makes it harder to visualize
where the arguments will be placed.
 In addition, if you specify the wrong indexes of
placeholders you will get a runtime error.
String Interpolation (cont)
 String interpolation fixes this, it allows us to use the
actual values as the placeholders inside the string.
 You simply use $ as a string prefix to signal the
compiler to use interpolation, then enclose the values
with curly brackets.
 Behind the scenes, the compiler will generate the
appropriate string format expression for you.
 Gives you all the power of string formatting, with
ability to visualize the values in the string itself.
String Interpolation (cont)
 So now, our example becomes:
 In addition, all string formatting options are available:
String Interpolation (cont)
 .NET has long had exception filtering:
Enhanced Exception Filtering
 Standard exception filtering is fine when you just care
about the type of the exception thrown.
 If you needed to make a decision to catch or not
based on logic – instead of type -- it’s clunky.
 For example, let’s assume we are dealing with a data
layer that throws a dependency exception with an
IsRetryable property.
 You may want to catch and handle if the exception is
retryable, but let it bubble up if not.
Enhanced Exception Filtering (cont)
 Let’s assume our exception looks like this:
Enhanced Exception Filtering (cont)
 To catch only retryable exceptions, we used to do this:
Enhanced Exception Filtering (cont)
 Now, with C# 6, you can specify a logical filter as well:
Enhanced Exception Filtering (cont)
 Now, you can have multiple catches on same type:
Enhanced Exception Filtering (cont)
 Filtering conditions do not have to involve the
exception, they can be any condition.
 Filters are checked in order for the same type, this
means that an unfiltered catch for a type must be
after all filtered catches for that type.
 Filter only evaluated if that exception type is thrown.
 If exception does not meet the filter, it is not
rethrown behind the scenes, it is simply not caught.
Enhanced Exception Filtering (cont)
 Have you ever consumed a web method (or other
API) with a deeply nested response?
 To be safe you have to do several layers of null checks
before getting to what you really want to check:
Null Conditional Operator
 C# 6 adds a new null conditional operator (?.) to
access a member if not null, or cascade if null.
 This would make our logic:
 In the above example, if response is null, or
response.Results is null, the whole result will be null.
Null Conditional Operator (cont)
 Note that all of these are legal, but different:
 The first throws if response null but cascades if
Results is null, the second cascades if response is null
but throws if Results is null, the third cascades both.
Null Conditional Operator (cont)
 A null-cascade that results in a value type will result in
a nullable value type:
 Though you can couple with the null-coallescing
operator (??) to provide a default if null.
Null Conditional Operator (cont)
 The null conditional operator is not just for
properties, you can use it for method calls as well.
Null Conditional Operator (cont)
 Also simplifies raising events:
Null Conditional Operator (cont)
 So what if you want to check for null before invoking
an indexer on an array, List<T>, etc?
 C# 6 has a syntax for null cascade on indexers (?[…]):
Null Conditional Operator (cont)
 C# 6 adds a lot of syntactical sugary goodness.
 Some of the features are more powerful than others,
but all have power to help increase maintainability
and readability of your code.
 Like any tools, know when to use them and when you
are overusing them.
 Visual Studio 2015 is currently in CTP6, moving to RC.
Summary
Questions?

More Related Content

What's hot

Commenting Best Practices
Commenting Best PracticesCommenting Best Practices
Commenting Best Practices
mh_azad
 
Cs30 New
Cs30 NewCs30 New
Comparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussionComparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussion
Dharmendra Prasad
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
Dror Helper
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Hossam Ghareeb
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
Sean McElrath
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: Fundamentals
Mahmoud Abdallah
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
Hawkman Academy
 
Automating C# Coding Standards using StyleCop and FxCop
Automating C# Coding Standards using StyleCop and FxCopAutomating C# Coding Standards using StyleCop and FxCop
Automating C# Coding Standards using StyleCop and FxCop
BlackRabbitCoder
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
Azilen Technologies Pvt. Ltd.
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
İbrahim Kürce
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
imedo.de
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
İbrahim Kürce
 
C#
C#C#
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practices
Tan Tran
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
Hari kiran G
 
Swift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming languageSwift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming language
Hossam Ghareeb
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
İbrahim Kürce
 
C#3.0 & Vb 9.0 Language Enhancments
C#3.0 & Vb 9.0 Language EnhancmentsC#3.0 & Vb 9.0 Language Enhancments
C#3.0 & Vb 9.0 Language Enhancmentstechfreak
 

What's hot (20)

Commenting Best Practices
Commenting Best PracticesCommenting Best Practices
Commenting Best Practices
 
Cs30 New
Cs30 NewCs30 New
Cs30 New
 
Comparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussionComparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussion
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: Fundamentals
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Automating C# Coding Standards using StyleCop and FxCop
Automating C# Coding Standards using StyleCop and FxCopAutomating C# Coding Standards using StyleCop and FxCop
Automating C# Coding Standards using StyleCop and FxCop
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
 
C#
C#C#
C#
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practices
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Swift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming languageSwift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming language
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
 
C#3.0 & Vb 9.0 Language Enhancments
C#3.0 & Vb 9.0 Language EnhancmentsC#3.0 & Vb 9.0 Language Enhancments
C#3.0 & Vb 9.0 Language Enhancments
 

Similar to The Little Wonders of C# 6

Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
ComicSansMS
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
BlackRabbitCoder
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
Apache Traffic Server
 
How to make fewer errors at the stage of code writing. Part N3.
How to make fewer errors at the stage of code writing. Part N3.How to make fewer errors at the stage of code writing. Part N3.
How to make fewer errors at the stage of code writing. Part N3.
PVS-Studio
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docx
dunhamadell
 
Flag Waiving
Flag WaivingFlag Waiving
Flag Waiving
Kevlin Henney
 
An Introduction To C++Templates
An Introduction To C++TemplatesAn Introduction To C++Templates
An Introduction To C++TemplatesGanesh Samarthyam
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5thConnex
 
Java Basics
Java BasicsJava Basics
Java Basics
shivamgarg_nitj
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
karymadelaneyrenne19
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
Jörn Guy Süß JGS
 
Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1
Vahid Farahmandian
 
Chapter3: fundamental programming
Chapter3: fundamental programmingChapter3: fundamental programming
Chapter3: fundamental programming
Ngeam Soly
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
Vishwa Mohan
 
Matopt
MatoptMatopt
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate JavaPhilip Johnson
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
C++ Homework Help
 
Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)
Unviersity of balochistan quetta
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and review
Abdullah Al-hazmy
 

Similar to The Little Wonders of C# 6 (20)

Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
How to make fewer errors at the stage of code writing. Part N3.
How to make fewer errors at the stage of code writing. Part N3.How to make fewer errors at the stage of code writing. Part N3.
How to make fewer errors at the stage of code writing. Part N3.
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docx
 
Flag Waiving
Flag WaivingFlag Waiving
Flag Waiving
 
C –FAQ:
C –FAQ:C –FAQ:
C –FAQ:
 
An Introduction To C++Templates
An Introduction To C++TemplatesAn Introduction To C++Templates
An Introduction To C++Templates
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1
 
Chapter3: fundamental programming
Chapter3: fundamental programmingChapter3: fundamental programming
Chapter3: fundamental programming
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Matopt
MatoptMatopt
Matopt
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and review
 

Recently uploaded

Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 

Recently uploaded (20)

Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 

The Little Wonders of C# 6

  • 1. The Little Wonders of C# 6 James Michael Hare Microsoft Visual C# MVP 4/27/2015 http://www.blackrabbitcoder.net/ @BlkRabbitCoder
  • 2.  The CTP for VS2015 is available for download  Includes the CTP for C# 6  Several new language features  No earth-shaking changes  Still compatible with .NET 4.5  Syntactical sugar to help reduce boiler-plate code  Helps improve code readability and maintainability Visual Studio 2015 is Upon Us!
  • 3.  The nameof() operator  Auto-property initialization  Indexed initializer lists  The using static directive  Method and property expressions  String interpolation  Enhanced exception filtering  The null conditional operator (?.) New C# 6 Features
  • 4.  Sometimes we want the name of an identifier as a string The nameof() Operator
  • 5.  We can hard-code, but if we rename the variable, we have to remember to update the string: The nameof() Operator (cont)
  • 6.  Now, you can get a string representation of an identifier with nameof(): The nameof() Operator (cont)
  • 7.  Before, if you wanted to default an auto-property to a non-default value, there wasn’t a simple way.  Either:  Create a backing field with initializer, then wrap in property  Or create an auto-property and then assign a value in the constructor  This should really be a simple, one-step process. Auto-Property Initialization
  • 8.  Now instead of this: Auto-Property Initialization (cont)
  • 9.  Or this…: Auto-Property Initialization (cont)
  • 10.  We can now do this!  Reduces several lines of boiler-plating. Auto-Property Initialization (cont)
  • 11.  In addition, you can use it even if the property has no setter (i.e. a truly read-only property): Auto-Property Initialization (cont)
  • 12.  Initializer lists now allow you to use indexers if the container supports them.  For example, you used to have to initialize a dictionary like this: Indexed Initialization Lists
  • 13.  But now you can use the indexer syntax instead:  The syntax is much cleaner and clearly identifies which string is the key and which is the value. Indexed Initialization Lists (cont)
  • 14.  Warning: just because a container supports indexing doesn’t mean initializing with it will always be logically sound…  For example:  What’s wrong with this? Indexed Initialization Lists (cont)
  • 15.  It is legal and compiles with no errors.  However, you are attempting to set elements that are beyond the list size, which List<T> doesn’t allow.  This is the same as doing this: Indexed Initialization Lists (cont)
  • 16.  So remember, it’s just syntactical sugar, it won’t stop you from performing a run-time illegal action.  To make that example work, you’d have to do something like: Indexed Initialization Lists (cont)
  • 17.  There are many static methods where the enclosing class mainly acts as an organization point (e.g. Math).  Sometimes, these class names give context to the static member being called.  Other times, they become repetitive clutter.  The using static declaration allows you to import the static members of a type into your namespace.  Also allows you to limit extension methods imported. The using static Directive
  • 18.  Consider the following:  A lot of these class names we can assume from context or are just organizational clutter. The using static Directive (cont)
  • 19.  If our program is a console app, we can probably assume the Console.  Similarly, the Math and Enumerable classes don’t add much. We already know what Pow() and Range() do.  Now, we can import the static members of these types with using static: The using static Directive (cont)
  • 20.  This would simplify our code to be:  We’ve removed a lot of redundant code without obscuring the clarity. The using static Directive (cont)
  • 21.  It’s not just for classes, you can import the static members of structs or enums.  For example, doing this:  Would allow us to do this: The using static Directive (cont)
  • 22.  Warning: just because you can do this doesn’t mean you always should.  Consider if you ran across this code:  There’s no context, so what the heck are we creating?  Here, the type would have given meaningful context: The using static Directive (cont)
  • 23.  Sometimes, we have properties or methods that are so simple, the body is mostly boilerplate Method and Property Expressions
  • 24.  You can now simplify with lambda expression syntax:  Handy for simple get-only properties, reduces the boilerplate around the get { } syntax.  Somewhat reduces syntax burden on methods. Method and Property Expressions (cont)
  • 25.  Consider building a string in a single statement with multiple components.  Typically we either use concatenation:  Or string formatting: String Interpolation
  • 26.  The problem with concatenation is that it breaks up the flow of the string you are building and makes it harder to envision the result.  Formatting helps solve this, but it removes the actual values from the string and makes it harder to visualize where the arguments will be placed.  In addition, if you specify the wrong indexes of placeholders you will get a runtime error. String Interpolation (cont)
  • 27.  String interpolation fixes this, it allows us to use the actual values as the placeholders inside the string.  You simply use $ as a string prefix to signal the compiler to use interpolation, then enclose the values with curly brackets.  Behind the scenes, the compiler will generate the appropriate string format expression for you.  Gives you all the power of string formatting, with ability to visualize the values in the string itself. String Interpolation (cont)
  • 28.  So now, our example becomes:  In addition, all string formatting options are available: String Interpolation (cont)
  • 29.  .NET has long had exception filtering: Enhanced Exception Filtering
  • 30.  Standard exception filtering is fine when you just care about the type of the exception thrown.  If you needed to make a decision to catch or not based on logic – instead of type -- it’s clunky.  For example, let’s assume we are dealing with a data layer that throws a dependency exception with an IsRetryable property.  You may want to catch and handle if the exception is retryable, but let it bubble up if not. Enhanced Exception Filtering (cont)
  • 31.  Let’s assume our exception looks like this: Enhanced Exception Filtering (cont)
  • 32.  To catch only retryable exceptions, we used to do this: Enhanced Exception Filtering (cont)
  • 33.  Now, with C# 6, you can specify a logical filter as well: Enhanced Exception Filtering (cont)
  • 34.  Now, you can have multiple catches on same type: Enhanced Exception Filtering (cont)
  • 35.  Filtering conditions do not have to involve the exception, they can be any condition.  Filters are checked in order for the same type, this means that an unfiltered catch for a type must be after all filtered catches for that type.  Filter only evaluated if that exception type is thrown.  If exception does not meet the filter, it is not rethrown behind the scenes, it is simply not caught. Enhanced Exception Filtering (cont)
  • 36.  Have you ever consumed a web method (or other API) with a deeply nested response?  To be safe you have to do several layers of null checks before getting to what you really want to check: Null Conditional Operator
  • 37.  C# 6 adds a new null conditional operator (?.) to access a member if not null, or cascade if null.  This would make our logic:  In the above example, if response is null, or response.Results is null, the whole result will be null. Null Conditional Operator (cont)
  • 38.  Note that all of these are legal, but different:  The first throws if response null but cascades if Results is null, the second cascades if response is null but throws if Results is null, the third cascades both. Null Conditional Operator (cont)
  • 39.  A null-cascade that results in a value type will result in a nullable value type:  Though you can couple with the null-coallescing operator (??) to provide a default if null. Null Conditional Operator (cont)
  • 40.  The null conditional operator is not just for properties, you can use it for method calls as well. Null Conditional Operator (cont)
  • 41.  Also simplifies raising events: Null Conditional Operator (cont)
  • 42.  So what if you want to check for null before invoking an indexer on an array, List<T>, etc?  C# 6 has a syntax for null cascade on indexers (?[…]): Null Conditional Operator (cont)
  • 43.  C# 6 adds a lot of syntactical sugary goodness.  Some of the features are more powerful than others, but all have power to help increase maintainability and readability of your code.  Like any tools, know when to use them and when you are overusing them.  Visual Studio 2015 is currently in CTP6, moving to RC. Summary