SlideShare a Scribd company logo
>< nextprevious
C#6A cleaner code
Clean up your code!
>< nextprevious
Philosophy design
No New Big features
… but many small ones to
to improve your code
Clean up your code!
>< nextprevious
Put C#6 In context
Let’s see how to improve our code with less
boiler plate and more meanings
>< nextprevious
The language
C#1
async/await
?
var, anonymous,
Lambdas, auto-
properties, line
Generics, partials,
iterators, nullables
C#2
C#4 C#3
C#5 C#6
History
dynamic, optional
parameters
2002 2005
2007
20152012
2010
>< nextprevious
Developers should write
their code to fit in a slide
News
01
Using Static classes
why bother with static class names?
02
03
04
>< nextprevious
String Interpolation
because string.format sucks
Getter only properties
because un-meaningful boiler plate
auto-properties initializers
because creating a backing field for
properties only don’t make sense
>< nextprevious
Using Static 01
using System;
public class Code
{
public void LogTime(string message)
{
Console.Write(DateTime.Now);
Console.WriteLine(message);
}
}
>< nextprevious
Using Static 01
using static System.Console;
using static System.DateTime;
public class Code
{
public void Print(string message)
{
Write(Now);
WriteLine(message);
}
}
>< nextprevious
Using Static 01
Console.Write(DateTime.Now);
Write(Now);
From a very technical line
You moved to a natural
language reading friendly
sentence
using static allows
removal of technical
boilerplate
>< nextprevious
String Interpolation 02
public void UserMessagesLog(
string message, User user)
{
var messageToLog =
string.Format("[{0}] {1} - {2}",
DateTime.Now,
user.Name,
message);
Console.WriteLine(messageToLog);
}
}
>< nextprevious
String Interpolation 02
public void UserMessagesLog(
string message, User user)
{
var messageToLog =
$"[{DateTime.Now}] {User.Name} - {message}"
Console.WriteLine(messageToLog);
}
}
>< nextprevious
String Interpolation 02
string.Format("[{0}] {1} - {2}",
DateTime.Now,
user.Name,
message);
$"[{DateTime.Now}] {User.Name} - {message}"
sounds good enough
for small strings, But…
we’re stupid, when you read the code,
there will be a context switch to
interpret the result of your string if the
value is not in the place you write it!
>< nextprevious
String Interpolation 02
public void UserMessagesLog(
string message, User user)
{
var messageToLog =
$"[{DateTime.Now}] {User.Name} - {message}"
Console.WriteLine(messageToLog);
}
}
Why waiting 15
years for that?
>< nextprevious
Getter only properties 03
public class Post
{
private string title;
public string Title
{
get{return title;}
}
public Post(string title)
{
this.title=title
}
}
C#2
>< nextprevious
Getter only properties 03
public class Post
{
public string Title { get;private set;}
public Post(string title)
{
Title=title
}
}
C#3
>< nextprevious
Getter only properties 03
public class Post
{
public string Title { get;}
public Post(string title)
{
Title=title
}
}
C#6
>< nextprevious
AutoProperties initializers 04
public class Post
{
private string id="new-post";
public string Id
{
get{return id;}
}
public Post()
{
}
} C#2
>< nextprevious
AutoProperties initializers 04
public class Post
{
public string Id {get;private set;}
public Post()
{
Id="new-post";
}
}
C#3
>< nextprevious
AutoProperties initializers 04
public class Post
{
public string Id {get;} = "new-post";
}
C#6
News
05
Expression bodied properties
because one expression is enough
06
07
08
>< nextprevious
Expression bodied methods
too much braces for a one expression
function
Index initializers
because initializer shortcuts are great
Null conditional operators
if null then null else arg…
>< nextprevious
Expression bodied props 05
public class Post
{
private DateTime created = DateTime.Now;
public DateTime Created
{
get{return created;}
}
public TimeSpan Elapsed
{
get {
return (DateTime.Now-Created);
}
}
}
C#3
>< nextprevious
Expression bodied props 05
public class Post
{
public DateTime Created {get;}
= DateTime.Now;
public TimeSpan Elapsed
=> (DateTime.Now-Created);
}
C#6
>< nextprevious
Expression bodied props 05
public class Post
{
public DateTime Created {get;}
= DateTime.Now;
public DateTime Updated
=> DateTime;
}
C#6
Spot the
difference
{get;} =
value is affected once for all, stored in an
hidden backing field
=>
represents an expression, newly evaluated on
each call
>< nextprevious
Expression Bodied Methods 06
public class Post
{
public string Title {get;set;}
public string BuildSlug()
{
return Title.ToLower().Replace(" ", "-"); 
}
}
C#3
>< nextprevious
Expression Bodied Methods 06
public class Post
{
public string Title {get;set;}
public string BuildSlug()
{
return Title.ToLower().Replace(" ", "-"); 
}
}
C#3
never been frustrated to have to write this {return}
boilerplate since you use the => construct with lambdas?
>< nextprevious
Expression Bodied Methods 06
public class Post
{
public string Title {get;set;}
public string BuildSlug()
=> Title
.ToLower()
.Replace(" ", "-");
}
C#6
>< nextprevious
Index initializers 07
public class Author
{
public Dictionary<string,string> Contacts
{get;private set;};
public Author()
{
Contacts = new Dictionary<string,string>();
Contacts.Add("mail", "demo@rui.fr");
Contacts.Add("twitter", "@rhwy");
Contacts.Add("github", "@rhwy");
}
}
C#2
>< nextprevious
Index initializers 07
public class Author
{
public Dictionary<string,string> Contacts
{get;}
= new Dictionary<string,string>() {
["mail"]="demo@rui.fr",
["twitter"]="@rhwy",
["github"]="@rhwy"
};
}
C#6
>< nextprevious
Index initializers 07
public class Author
{
public Dictionary<string,string> Contacts
{get;}
= new Dictionary<string,string>() {
{"mail","demo@rui.fr"},
{"twitter","@rhwy"},
{"github","@rhwy"}
};
}
C#3
>< nextprevious
Null Conditional Operators 08
public class Post
{
//"rui carvalho"
public string Author {get;private set;};
//=>"Rui Carvalho"
public string GetPrettyName()
{
if(Author!=null)
{
if(Author.Contains(" "))
{
string result;
var items=Author.Split(" ");
forEach(var word in items)
{
result+=word.SubString(0,1).ToUpper()
+word.SubString(1).ToLower()
+ " ";
}
return result.Trim();
}
}
return Author;
}
}
C#3
>< nextprevious
Null Conditional Operators 08
public class Post
{
//"rui carvalho"
public string Author {get;private set;};
//=>"Rui Carvalho"
public string GetPrettyName()
=> (string.Join("",
Author?.Split(' ')
.ToList()
.Select( word=>
word.Substring(0,1).ToUpper()
+word.Substring(1).ToLower()
+ " ")
)).Trim();
C#6
>< nextprevious
Null Conditional Operators 08
public class Post
{
//"rui carvalho"
public string Author {get;private set;};
//=>"Rui Carvalho"
public string GetPrettyName()
=> (string.Join("",
Author?.Split(' ')
.ToList()
.Select( word=>
word.Substring(0,1).ToUpper()
+word.Substring(1).ToLower()
+ " ")
)).Trim();
C#6
We have now one
expression only but
maybe not that clear or
testable ?
>< nextprevious
Null Conditional Operators 08
public string PrettifyWord (string word)
=>
word.Substring(0,1).ToUpper()
+word.Substring(1).ToLower()
+ " ";
public IEnumerable<string>
PrettifyTextIfExists(string phrase)
=> phrase?
.Split(' ')
.Select( PrettifyWord);
public string GetPrettyName()
=> string
.Join("",PrettifyTextIfExists(Author))
.Trim();
C#6
Refactoring !
We have now 3 small
independent functions with
Names and meanings
News
09
Exception filters
not new in .Net
10
11
12
>< nextprevious
nameof Operator
consistent refactorings
await in catch
who never complained about that?
and in finally
the last step
News
09
Exception filters
not new in .Net
10
11
12
>< nextprevious
nameof Operator
consistent refactorings
await in catch
who never complained about that?
and in finally
the last step
these ones are just goodimprovements but not thatimportant for our code
readability
>< nextprevious
Exception Filters 09
try {
//production code
}
catch (HttpException ex)
{
if(ex.StatusCode==500)
//do some specific crash scenario
if(ex.StatusCode==400)
//tell client that he’s stupid
}
catch (Exception otherErrors)
{
// ...
}
C#2
>< nextprevious
Exception Filters 09
try {
//production code
}
catch (HttpException ex) when (ex.StatusCode == 500)
{
//do some specific crash scenario
}
catch (HttpException ex) when (ex.StatusCode == 400)
{
//tell the client he’s stupid
}
catch (Exception otherException)
{
// ...
}
C#6
>< nextprevious
nameof Operator 10
public string SomeMethod (string word)
{
if(word == null)
throw new Exception("word is null");
return word;
}
C#3
>< nextprevious
nameof Operator 10
public string SomeMethod (string text)
{
if(word == null)
throw new Exception("word is null");
return word;
}
C#3
Refactoring
arg, information
lost!
>< nextprevious
nameof Operator 10
public string SomeMethod (string word)
{
if(word == null)
throw new Exception(
$"{nameof(word)} is null");
return word;
}
C#6
parameter name is now pure
code & support refactoring
>< nextprevious
await in catch 11
try {
return await something();
}
catch (HttpException ex)
{
error = ex;
}
return await CrashLogger.ServerError(error);
C#5
>< nextprevious
await in catch 11
try {
await something();
}
catch (HttpException ex)
{
await CrashLogger.ServerError(ex);
}
C#6
>< nextprevious
await in finally 12
try {
return await Persistence.Query(query);
}
catch (PersistenceException ex)
{
await CrashLogger.ServerError(ex);
}
finally
{
await Persistence.Close();
} C#6
>< nextprevious
To Finish
C#6 helps to be more functional & write cleaner code by
removing lots of boilerplate!
refactoring to small
functions, add new words to
your app vocabulary
>< nextprevious
Thanks
@rhwy
ncrafts.io
altnet.fr
rui.io

More Related Content

PDF
C++ for Java Developers (JavaZone Academy 2018)
PDF
C++ for Java Developers (SwedenCpp Meetup 2017)
ODP
Ast transformations
PPTX
Building native Android applications with Mirah and Pindah
PPTX
Java concurrency questions and answers
PDF
DRYing to Monad in Java8
ODP
AST Transformations
PDF
Lambda and Stream Master class - part 1
C++ for Java Developers (JavaZone Academy 2018)
C++ for Java Developers (SwedenCpp Meetup 2017)
Ast transformations
Building native Android applications with Mirah and Pindah
Java concurrency questions and answers
DRYing to Monad in Java8
AST Transformations
Lambda and Stream Master class - part 1

What's hot (20)

PDF
Java SE 8 for Java EE developers
PPTX
Why you should be using the shiny new C# 6.0 features now!
PDF
Currying and Partial Function Application (PFA)
PDF
Java Full Throttle
PDF
Lambdas and Streams Master Class Part 2
PDF
IronSmalltalk
PPTX
Navigating the xDD Alphabet Soup
PDF
Developing Useful APIs
PDF
Kotlin Developer Starter in Android projects
PDF
Introduction to cdi given at java one 2014
PDF
Creating Lazy stream in CSharp
PDF
Little Helpers for Android Development with Kotlin
PDF
Anatomy of a Gradle plugin
PPTX
Typescript barcelona
ODP
Lambda Chops - Recipes for Simpler, More Expressive Code
PDF
Kotlin advanced - language reference for android developers
PDF
Building Maintainable Applications in Apex
PDF
ActiveRecord Query Interface (2), Season 2
KEY
Mirah Talk for Boulder Ruby Group
PDF
Core Java - Quiz Questions - Bug Hunt
Java SE 8 for Java EE developers
Why you should be using the shiny new C# 6.0 features now!
Currying and Partial Function Application (PFA)
Java Full Throttle
Lambdas and Streams Master Class Part 2
IronSmalltalk
Navigating the xDD Alphabet Soup
Developing Useful APIs
Kotlin Developer Starter in Android projects
Introduction to cdi given at java one 2014
Creating Lazy stream in CSharp
Little Helpers for Android Development with Kotlin
Anatomy of a Gradle plugin
Typescript barcelona
Lambda Chops - Recipes for Simpler, More Expressive Code
Kotlin advanced - language reference for android developers
Building Maintainable Applications in Apex
ActiveRecord Query Interface (2), Season 2
Mirah Talk for Boulder Ruby Group
Core Java - Quiz Questions - Bug Hunt
Ad

Viewers also liked (18)

PDF
1165 hong kong's unique protestors
PPT
Pérolas das avaliações de conhecimento
PDF
Workshop - Links Patrocinados e SEO
PPTX
ApresentaçãO Em PúBlico (Veronica)
PPTX
O real e o supra real. seminário de teologia da saúde. iv
PPT
Carmof oa
PPT
Utilização dos recursos linguísticos na publicidade
PPT
Dino preti
PPT
Significado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
PPTX
O signo linguístico em saussure, hjelmslev e
PPT
Signo linguìstico
PPT
Signos Visuais
PDF
Figuras de linguagem: 25 propagandas. Exercício 2.
PDF
Figuras de linguagem em propagandas
PPTX
Figuras de linguagem slide
PPTX
Figuras de linguagem slide
PDF
Semiótica - ícone, índice e símbolo
PPT
Signos | Semiótica: símbolo, índice e ícone
1165 hong kong's unique protestors
Pérolas das avaliações de conhecimento
Workshop - Links Patrocinados e SEO
ApresentaçãO Em PúBlico (Veronica)
O real e o supra real. seminário de teologia da saúde. iv
Carmof oa
Utilização dos recursos linguísticos na publicidade
Dino preti
Significado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
O signo linguístico em saussure, hjelmslev e
Signo linguìstico
Signos Visuais
Figuras de linguagem: 25 propagandas. Exercício 2.
Figuras de linguagem em propagandas
Figuras de linguagem slide
Figuras de linguagem slide
Semiótica - ícone, índice e símbolo
Signos | Semiótica: símbolo, índice e ícone
Ad

Similar to Clean up your code with C#6 (20)

PPTX
C#.net evolution part 2
PPTX
C# 6.0 Introduction
PPTX
.NET Foundation, Future of .NET and C#
PPT
Linq intro
PDF
Why Java Sucks and C# Rocks (Final)
PPT
TechTalk - Dotnet
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
PPSX
What's new in C# 6 - NetPonto Porto 20160116
PDF
.gradle 파일 정독해보기
PPTX
Annotation processor and compiler plugin
PPTX
C#6 - The New Stuff
PDF
Дмитрий Верескун «Синтаксический сахар C#»
PDF
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
PPTX
Static code analysis: what? how? why?
PDF
The First C# Project Analyzed
PDF
Ecmascript 2015 – best of new features()
DOCX
C# 6.0
PDF
C++ Programming
PPT
Visual studio 2008
C#.net evolution part 2
C# 6.0 Introduction
.NET Foundation, Future of .NET and C#
Linq intro
Why Java Sucks and C# Rocks (Final)
TechTalk - Dotnet
Intro To JavaScript Unit Testing - Ran Mizrahi
What's new in C# 6 - NetPonto Porto 20160116
.gradle 파일 정독해보기
Annotation processor and compiler plugin
C#6 - The New Stuff
Дмитрий Верескун «Синтаксический сахар C#»
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
Static code analysis: what? how? why?
The First C# Project Analyzed
Ecmascript 2015 – best of new features()
C# 6.0
C++ Programming
Visual studio 2008

More from Rui Carvalho (15)

PDF
Agile Feedback Loops
PDF
NewCrafts 2017 Conference Opening
PPTX
Cqrs Ignite
PDF
AltNet fr talks #2016.11 - news
PDF
Patience, the art of taking his time
PDF
Ncrafts 2016 opening notes
PDF
Code Cooking
PDF
Feedback Loops v4x3 Lightening
PDF
Feedback Loops...to infinity, and beyond!
PDF
Simple Code
PDF
Simplicity 2.0 - Get the power back
PPTX
SPA avec Angular et SignalR (FR)
PPTX
My Git workflow
PPTX
Simplicity - develop modern web apps with tiny frameworks and tools
PPT
.Net pour le développeur Java - une source d'inspiration?
Agile Feedback Loops
NewCrafts 2017 Conference Opening
Cqrs Ignite
AltNet fr talks #2016.11 - news
Patience, the art of taking his time
Ncrafts 2016 opening notes
Code Cooking
Feedback Loops v4x3 Lightening
Feedback Loops...to infinity, and beyond!
Simple Code
Simplicity 2.0 - Get the power back
SPA avec Angular et SignalR (FR)
My Git workflow
Simplicity - develop modern web apps with tiny frameworks and tools
.Net pour le développeur Java - une source d'inspiration?

Recently uploaded (20)

PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
AI in Product Development-omnex systems
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
medical staffing services at VALiNTRY
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Digital Strategies for Manufacturing Companies
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
System and Network Administraation Chapter 3
PPTX
history of c programming in notes for students .pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
System and Network Administration Chapter 2
Navsoft: AI-Powered Business Solutions & Custom Software Development
PTS Company Brochure 2025 (1).pdf.......
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Internet Downloader Manager (IDM) Crack 6.42 Build 41
AI in Product Development-omnex systems
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
medical staffing services at VALiNTRY
Which alternative to Crystal Reports is best for small or large businesses.pdf
How Creative Agencies Leverage Project Management Software.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Digital Strategies for Manufacturing Companies
Design an Analysis of Algorithms I-SECS-1021-03
Odoo POS Development Services by CandidRoot Solutions
wealthsignaloriginal-com-DS-text-... (1).pdf
Odoo Companies in India – Driving Business Transformation.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
System and Network Administraation Chapter 3
history of c programming in notes for students .pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
System and Network Administration Chapter 2

Clean up your code with C#6

  • 2. Clean up your code! >< nextprevious Philosophy design No New Big features … but many small ones to to improve your code
  • 3. Clean up your code! >< nextprevious Put C#6 In context Let’s see how to improve our code with less boiler plate and more meanings
  • 4. >< nextprevious The language C#1 async/await ? var, anonymous, Lambdas, auto- properties, line Generics, partials, iterators, nullables C#2 C#4 C#3 C#5 C#6 History dynamic, optional parameters 2002 2005 2007 20152012 2010
  • 5. >< nextprevious Developers should write their code to fit in a slide
  • 6. News 01 Using Static classes why bother with static class names? 02 03 04 >< nextprevious String Interpolation because string.format sucks Getter only properties because un-meaningful boiler plate auto-properties initializers because creating a backing field for properties only don’t make sense
  • 7. >< nextprevious Using Static 01 using System; public class Code { public void LogTime(string message) { Console.Write(DateTime.Now); Console.WriteLine(message); } }
  • 8. >< nextprevious Using Static 01 using static System.Console; using static System.DateTime; public class Code { public void Print(string message) { Write(Now); WriteLine(message); } }
  • 9. >< nextprevious Using Static 01 Console.Write(DateTime.Now); Write(Now); From a very technical line You moved to a natural language reading friendly sentence using static allows removal of technical boilerplate
  • 10. >< nextprevious String Interpolation 02 public void UserMessagesLog( string message, User user) { var messageToLog = string.Format("[{0}] {1} - {2}", DateTime.Now, user.Name, message); Console.WriteLine(messageToLog); } }
  • 11. >< nextprevious String Interpolation 02 public void UserMessagesLog( string message, User user) { var messageToLog = $"[{DateTime.Now}] {User.Name} - {message}" Console.WriteLine(messageToLog); } }
  • 12. >< nextprevious String Interpolation 02 string.Format("[{0}] {1} - {2}", DateTime.Now, user.Name, message); $"[{DateTime.Now}] {User.Name} - {message}" sounds good enough for small strings, But… we’re stupid, when you read the code, there will be a context switch to interpret the result of your string if the value is not in the place you write it!
  • 13. >< nextprevious String Interpolation 02 public void UserMessagesLog( string message, User user) { var messageToLog = $"[{DateTime.Now}] {User.Name} - {message}" Console.WriteLine(messageToLog); } } Why waiting 15 years for that?
  • 14. >< nextprevious Getter only properties 03 public class Post { private string title; public string Title { get{return title;} } public Post(string title) { this.title=title } } C#2
  • 15. >< nextprevious Getter only properties 03 public class Post { public string Title { get;private set;} public Post(string title) { Title=title } } C#3
  • 16. >< nextprevious Getter only properties 03 public class Post { public string Title { get;} public Post(string title) { Title=title } } C#6
  • 17. >< nextprevious AutoProperties initializers 04 public class Post { private string id="new-post"; public string Id { get{return id;} } public Post() { } } C#2
  • 18. >< nextprevious AutoProperties initializers 04 public class Post { public string Id {get;private set;} public Post() { Id="new-post"; } } C#3
  • 19. >< nextprevious AutoProperties initializers 04 public class Post { public string Id {get;} = "new-post"; } C#6
  • 20. News 05 Expression bodied properties because one expression is enough 06 07 08 >< nextprevious Expression bodied methods too much braces for a one expression function Index initializers because initializer shortcuts are great Null conditional operators if null then null else arg…
  • 21. >< nextprevious Expression bodied props 05 public class Post { private DateTime created = DateTime.Now; public DateTime Created { get{return created;} } public TimeSpan Elapsed { get { return (DateTime.Now-Created); } } } C#3
  • 22. >< nextprevious Expression bodied props 05 public class Post { public DateTime Created {get;} = DateTime.Now; public TimeSpan Elapsed => (DateTime.Now-Created); } C#6
  • 23. >< nextprevious Expression bodied props 05 public class Post { public DateTime Created {get;} = DateTime.Now; public DateTime Updated => DateTime; } C#6 Spot the difference {get;} = value is affected once for all, stored in an hidden backing field => represents an expression, newly evaluated on each call
  • 24. >< nextprevious Expression Bodied Methods 06 public class Post { public string Title {get;set;} public string BuildSlug() { return Title.ToLower().Replace(" ", "-");  } } C#3
  • 25. >< nextprevious Expression Bodied Methods 06 public class Post { public string Title {get;set;} public string BuildSlug() { return Title.ToLower().Replace(" ", "-");  } } C#3 never been frustrated to have to write this {return} boilerplate since you use the => construct with lambdas?
  • 26. >< nextprevious Expression Bodied Methods 06 public class Post { public string Title {get;set;} public string BuildSlug() => Title .ToLower() .Replace(" ", "-"); } C#6
  • 27. >< nextprevious Index initializers 07 public class Author { public Dictionary<string,string> Contacts {get;private set;}; public Author() { Contacts = new Dictionary<string,string>(); Contacts.Add("mail", "demo@rui.fr"); Contacts.Add("twitter", "@rhwy"); Contacts.Add("github", "@rhwy"); } } C#2
  • 28. >< nextprevious Index initializers 07 public class Author { public Dictionary<string,string> Contacts {get;} = new Dictionary<string,string>() { ["mail"]="demo@rui.fr", ["twitter"]="@rhwy", ["github"]="@rhwy" }; } C#6
  • 29. >< nextprevious Index initializers 07 public class Author { public Dictionary<string,string> Contacts {get;} = new Dictionary<string,string>() { {"mail","demo@rui.fr"}, {"twitter","@rhwy"}, {"github","@rhwy"} }; } C#3
  • 30. >< nextprevious Null Conditional Operators 08 public class Post { //"rui carvalho" public string Author {get;private set;}; //=>"Rui Carvalho" public string GetPrettyName() { if(Author!=null) { if(Author.Contains(" ")) { string result; var items=Author.Split(" "); forEach(var word in items) { result+=word.SubString(0,1).ToUpper() +word.SubString(1).ToLower() + " "; } return result.Trim(); } } return Author; } } C#3
  • 31. >< nextprevious Null Conditional Operators 08 public class Post { //"rui carvalho" public string Author {get;private set;}; //=>"Rui Carvalho" public string GetPrettyName() => (string.Join("", Author?.Split(' ') .ToList() .Select( word=> word.Substring(0,1).ToUpper() +word.Substring(1).ToLower() + " ") )).Trim(); C#6
  • 32. >< nextprevious Null Conditional Operators 08 public class Post { //"rui carvalho" public string Author {get;private set;}; //=>"Rui Carvalho" public string GetPrettyName() => (string.Join("", Author?.Split(' ') .ToList() .Select( word=> word.Substring(0,1).ToUpper() +word.Substring(1).ToLower() + " ") )).Trim(); C#6 We have now one expression only but maybe not that clear or testable ?
  • 33. >< nextprevious Null Conditional Operators 08 public string PrettifyWord (string word) => word.Substring(0,1).ToUpper() +word.Substring(1).ToLower() + " "; public IEnumerable<string> PrettifyTextIfExists(string phrase) => phrase? .Split(' ') .Select( PrettifyWord); public string GetPrettyName() => string .Join("",PrettifyTextIfExists(Author)) .Trim(); C#6 Refactoring ! We have now 3 small independent functions with Names and meanings
  • 34. News 09 Exception filters not new in .Net 10 11 12 >< nextprevious nameof Operator consistent refactorings await in catch who never complained about that? and in finally the last step
  • 35. News 09 Exception filters not new in .Net 10 11 12 >< nextprevious nameof Operator consistent refactorings await in catch who never complained about that? and in finally the last step these ones are just goodimprovements but not thatimportant for our code readability
  • 36. >< nextprevious Exception Filters 09 try { //production code } catch (HttpException ex) { if(ex.StatusCode==500) //do some specific crash scenario if(ex.StatusCode==400) //tell client that he’s stupid } catch (Exception otherErrors) { // ... } C#2
  • 37. >< nextprevious Exception Filters 09 try { //production code } catch (HttpException ex) when (ex.StatusCode == 500) { //do some specific crash scenario } catch (HttpException ex) when (ex.StatusCode == 400) { //tell the client he’s stupid } catch (Exception otherException) { // ... } C#6
  • 38. >< nextprevious nameof Operator 10 public string SomeMethod (string word) { if(word == null) throw new Exception("word is null"); return word; } C#3
  • 39. >< nextprevious nameof Operator 10 public string SomeMethod (string text) { if(word == null) throw new Exception("word is null"); return word; } C#3 Refactoring arg, information lost!
  • 40. >< nextprevious nameof Operator 10 public string SomeMethod (string word) { if(word == null) throw new Exception( $"{nameof(word)} is null"); return word; } C#6 parameter name is now pure code & support refactoring
  • 41. >< nextprevious await in catch 11 try { return await something(); } catch (HttpException ex) { error = ex; } return await CrashLogger.ServerError(error); C#5
  • 42. >< nextprevious await in catch 11 try { await something(); } catch (HttpException ex) { await CrashLogger.ServerError(ex); } C#6
  • 43. >< nextprevious await in finally 12 try { return await Persistence.Query(query); } catch (PersistenceException ex) { await CrashLogger.ServerError(ex); } finally { await Persistence.Close(); } C#6
  • 44. >< nextprevious To Finish C#6 helps to be more functional & write cleaner code by removing lots of boilerplate! refactoring to small functions, add new words to your app vocabulary