SlideShare a Scribd company logo
1 of 45
Download to read offline
>< 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

What's hot

Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developersJosé Paumard
 
Why you should be using the shiny new C# 6.0 features now!
Why you should be using the shiny new C# 6.0 features now!Why you should be using the shiny new C# 6.0 features now!
Why you should be using the shiny new C# 6.0 features now!Eric Phan
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Dhaval Dalal
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 
IronSmalltalk
IronSmalltalkIronSmalltalk
IronSmalltalkESUG
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupDror Helper
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIsDmitry Buzdin
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014Antoine Sabot-Durand
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharpDhaval Dalal
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinKai Koenig
 
Anatomy of a Gradle plugin
Anatomy of a Gradle pluginAnatomy of a Gradle plugin
Anatomy of a Gradle pluginDmytro Zaitsev
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
Building Maintainable Applications in Apex
Building Maintainable Applications in ApexBuilding Maintainable Applications in Apex
Building Maintainable Applications in ApexJeffrey Kemp
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2RORLAB
 
Mirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby GroupMirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby Groupbaroquebobcat
 

What's hot (20)

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

Viewers also liked

1165 hong kong's unique protestors
1165 hong kong's unique protestors1165 hong kong's unique protestors
1165 hong kong's unique protestorsNext2ndOpinions
 
Pérolas das avaliações de conhecimento
Pérolas das avaliações de conhecimentoPérolas das avaliações de conhecimento
Pérolas das avaliações de conhecimentoRoger William Campos
 
Workshop - Links Patrocinados e SEO
Workshop - Links Patrocinados e SEOWorkshop - Links Patrocinados e SEO
Workshop - Links Patrocinados e SEOYogh
 
ApresentaçãO Em PúBlico (Veronica)
ApresentaçãO Em PúBlico (Veronica)ApresentaçãO Em PúBlico (Veronica)
ApresentaçãO Em PúBlico (Veronica)veronica nascimento
 
O real e o supra real. seminário de teologia da saúde. iv
O real e o supra real. seminário de teologia da saúde. ivO real e o supra real. seminário de teologia da saúde. iv
O real e o supra real. seminário de teologia da saúde. ivArtemosfera Cia de Artes
 
Utilização dos recursos linguísticos na publicidade
Utilização dos recursos linguísticos na publicidadeUtilização dos recursos linguísticos na publicidade
Utilização dos recursos linguísticos na publicidadeBeth Cordeiro
 
Significado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
Significado e Significante e a Dinâmica do Inconsciente na Terapia RegressivaSignificado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
Significado e Significante e a Dinâmica do Inconsciente na Terapia RegressivaGSArt Web Solutions
 
Semiótica é Experiência
Semiótica é ExperiênciaSemiótica é Experiência
Semiótica é ExperiênciaCarol Reine
 
O signo linguístico em saussure, hjelmslev e
O signo linguístico em saussure, hjelmslev eO signo linguístico em saussure, hjelmslev e
O signo linguístico em saussure, hjelmslev eUnternbaumen
 
Figuras de linguagem: 25 propagandas. Exercício 2.
Figuras de linguagem: 25 propagandas. Exercício 2.Figuras de linguagem: 25 propagandas. Exercício 2.
Figuras de linguagem: 25 propagandas. Exercício 2.Cláudia Heloísa
 
Figuras de linguagem em propagandas
Figuras de linguagem em propagandasFiguras de linguagem em propagandas
Figuras de linguagem em propagandasCláudia Heloísa
 
Figuras de linguagem slide
Figuras de linguagem   slideFiguras de linguagem   slide
Figuras de linguagem slideJaciara Mota
 
Figuras de linguagem slide
Figuras de linguagem slideFiguras de linguagem slide
Figuras de linguagem slideIvana Bastos
 
Semiótica - ícone, índice e símbolo
Semiótica - ícone, índice e símboloSemiótica - ícone, índice e símbolo
Semiótica - ícone, índice e símboloBruno Santos
 
Signos | Semiótica: símbolo, índice e ícone
Signos | Semiótica: símbolo, índice e íconeSignos | Semiótica: símbolo, índice e ícone
Signos | Semiótica: símbolo, índice e íconeThaís Rodrigues
 

Viewers also liked (19)

1165 hong kong's unique protestors
1165 hong kong's unique protestors1165 hong kong's unique protestors
1165 hong kong's unique protestors
 
Pérolas das avaliações de conhecimento
Pérolas das avaliações de conhecimentoPérolas das avaliações de conhecimento
Pérolas das avaliações de conhecimento
 
Workshop - Links Patrocinados e SEO
Workshop - Links Patrocinados e SEOWorkshop - Links Patrocinados e SEO
Workshop - Links Patrocinados e SEO
 
ApresentaçãO Em PúBlico (Veronica)
ApresentaçãO Em PúBlico (Veronica)ApresentaçãO Em PúBlico (Veronica)
ApresentaçãO Em PúBlico (Veronica)
 
O real e o supra real. seminário de teologia da saúde. iv
O real e o supra real. seminário de teologia da saúde. ivO real e o supra real. seminário de teologia da saúde. iv
O real e o supra real. seminário de teologia da saúde. iv
 
Carmof oa
Carmof oaCarmof oa
Carmof oa
 
Utilização dos recursos linguísticos na publicidade
Utilização dos recursos linguísticos na publicidadeUtilização dos recursos linguísticos na publicidade
Utilização dos recursos linguísticos na publicidade
 
Dino preti
Dino pretiDino preti
Dino preti
 
Significado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
Significado e Significante e a Dinâmica do Inconsciente na Terapia RegressivaSignificado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
Significado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
 
Semiótica é Experiência
Semiótica é ExperiênciaSemiótica é Experiência
Semiótica é Experiência
 
O signo linguístico em saussure, hjelmslev e
O signo linguístico em saussure, hjelmslev eO signo linguístico em saussure, hjelmslev e
O signo linguístico em saussure, hjelmslev e
 
Signo linguìstico
Signo linguìsticoSigno linguìstico
Signo linguìstico
 
Signos Visuais
Signos VisuaisSignos Visuais
Signos Visuais
 
Figuras de linguagem: 25 propagandas. Exercício 2.
Figuras de linguagem: 25 propagandas. Exercício 2.Figuras de linguagem: 25 propagandas. Exercício 2.
Figuras de linguagem: 25 propagandas. Exercício 2.
 
Figuras de linguagem em propagandas
Figuras de linguagem em propagandasFiguras de linguagem em propagandas
Figuras de linguagem em propagandas
 
Figuras de linguagem slide
Figuras de linguagem   slideFiguras de linguagem   slide
Figuras de linguagem slide
 
Figuras de linguagem slide
Figuras de linguagem slideFiguras de linguagem slide
Figuras de linguagem slide
 
Semiótica - ícone, índice e símbolo
Semiótica - ícone, índice e símboloSemiótica - ícone, índice e símbolo
Semiótica - ícone, índice e símbolo
 
Signos | Semiótica: símbolo, índice e ícone
Signos | Semiótica: símbolo, índice e íconeSignos | Semiótica: símbolo, índice e ícone
Signos | Semiótica: símbolo, índice e ícone
 

Similar to Clean up your code with C#6

C# 6.0 Introduction
C# 6.0 IntroductionC# 6.0 Introduction
C# 6.0 IntroductionOlav Haugen
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#Bertrand Le Roy
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116Paulo Morgado
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기경주 전
 
Annotation processor and compiler plugin
Annotation processor and compiler pluginAnnotation processor and compiler plugin
Annotation processor and compiler pluginOleksandr Radchykov
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»SpbDotNet Community
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfARORACOCKERY2111
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?Andrey Karpov
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project AnalyzedPVS-Studio
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Miłosz Sobczak
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008Luis Enrique
 

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

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

More from Rui Carvalho

Agile Feedback Loops
Agile Feedback LoopsAgile Feedback Loops
Agile Feedback LoopsRui Carvalho
 
NewCrafts 2017 Conference Opening
NewCrafts 2017 Conference OpeningNewCrafts 2017 Conference Opening
NewCrafts 2017 Conference OpeningRui Carvalho
 
AltNet fr talks #2016.11 - news
AltNet fr talks #2016.11 - newsAltNet fr talks #2016.11 - news
AltNet fr talks #2016.11 - newsRui Carvalho
 
Patience, the art of taking his time
Patience, the art of taking his timePatience, the art of taking his time
Patience, the art of taking his timeRui Carvalho
 
Ncrafts 2016 opening notes
Ncrafts 2016 opening notesNcrafts 2016 opening notes
Ncrafts 2016 opening notesRui Carvalho
 
Feedback Loops v4x3 Lightening
Feedback Loops v4x3 Lightening Feedback Loops v4x3 Lightening
Feedback Loops v4x3 Lightening Rui Carvalho
 
Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!Rui Carvalho
 
Simplicity 2.0 - Get the power back
Simplicity 2.0 - Get the power backSimplicity 2.0 - Get the power back
Simplicity 2.0 - Get the power backRui Carvalho
 
SPA avec Angular et SignalR (FR)
SPA avec Angular et SignalR (FR)SPA avec Angular et SignalR (FR)
SPA avec Angular et SignalR (FR)Rui Carvalho
 
Simplicity - develop modern web apps with tiny frameworks and tools
Simplicity - develop modern web apps with tiny frameworks and toolsSimplicity - develop modern web apps with tiny frameworks and tools
Simplicity - develop modern web apps with tiny frameworks and toolsRui Carvalho
 
.Net pour le développeur Java - une source d'inspiration?
.Net pour le développeur Java - une source d'inspiration?.Net pour le développeur Java - une source d'inspiration?
.Net pour le développeur Java - une source d'inspiration?Rui Carvalho
 

More from Rui Carvalho (15)

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

Recently uploaded

Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 

Recently uploaded (20)

Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 

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