SlideShare a Scribd company logo
What’s New In C# 6
Paulo Morgado
http://netponto.org9ª Reunião Presencial - Porto - 16/01/2016
Paulo Morgado
Agenda
• Improvements in Auto-Properties
• Expression Bodied Function Members
• The 'using static' Directive
• Null-Conditional Operator
• String Interpolation
• 'nameof' Expressions
• Add Extension Methods in Collection Initializers
• Index Initializers
• Exception Filters
• 'await' in 'catch' and 'finally' blocks
• C# Interactive
Improvements in Auto-Properties
Initializers for Auto-Properties
public class Person
{
private string firstName = "Jane"
private string lastName = "Doe";
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
Improvements in Auto-Properties
Initializers for Auto-Properties
public class Person
{
public string FirstName { get; set; } = "Jane";
public string LastName { get; set; } = "Doe";
}
C# 6
Improvements in Auto-Properties
Read-Only Auto-Properties
public class Person
{
private readonly string firstName = "Jane";
private readonly string lastName = "Doe";
public string FirstName
{
get { return firstName; }
}
public string LastName
{
get { return lastName; }
}
// ...
public Person(string first, string last)
{
firstName = first;
lastName = last;
}
}
Improvements in Auto-Properties
Read-Only Auto-Properties
public class Person
{
public string FirstName { get; } = "Jane";
public string LastName { get; } = "Doe";
// ...
public Person(string first, string last)
{
FirstName = first;
LastName = last;
}
}
C# 6
Expression Bodied Function Members
Expression Bodied Method-Like Function Members
public Point Move(int dx, int dy)
{
return new Point(x + dx, y + dy);
}
public static Complex operator +(Complex a, Complex b)
{
return a.Add(b);
}
public static implicit operator string(Person p)
{
return p.First + " " + p.Last;
}
Expression Bodied Function Members
Expression Bodied Method-Like Function Members
public Point Move(int dx, int dy) => new Point(x + dx, y + dy);
public static Complex operator +(Complex a, Complex b) => a.Add(b);
public static implicit operator string (Person p) => p.First + " " + p.Last;
C# 6
Expression Bodied Function Members
Expression Bodied Property-Like Function Members
public string Name
{
get { return First + " " + Last; }
}
public Person this[long id]
{
get { return store.LookupPerson(id); }
}
Expression Bodied Function Members
Expression Bodied Property-Like Function Members
public string Name => First + " " + Last;
public Person this[long id] => store.LookupPerson(id);
C# 6
The 'using static' Directive
using System;
class Program
{
static void Main()
{
Console.WriteLine(Math.Sqrt(3 * 3 + 4 * 4));
Console.WriteLine(DayOfWeek.Friday - DayOfWeek.Monday);
}
}
The 'using static' Directive
using static System.Console;
using static System.Math;
using static System.DayOfWeek;
class Program
{
static void Main()
{
WriteLine(Sqrt(3 * 3 + 4 * 4));
WriteLine(Friday - Monday);
}
}
C# 6
The 'using static' Directive
Extension Methods
using static System.Linq.Enumerable; // The type, not the namespace
class Program
{
static void Main()
{
var range = Range(5, 17); // Ok: not extension
var odd = Where(range, i => i % 2 == 1); // Error, not in scope
var even = range.Where(i => i % 2 == 0); // Ok
}
}
C# 6
Null-Conditional Operator
Property and Method Invocation
int? nullable = (people != null) ? new int?(people.Length) : null;
Person person = (people != null) ? people[0] : null;
int? first = (people != null) ? people[0].Orders.Count() : (int?)null;
Null-Conditional Operator
Property and Method Invocation
int? length = people?.Length; // null if people is null
Person first = people?[0]; // null if people is null
int length = people?.Length ?? 0; // 0 if people is null
int? first = people?[0].Orders.Count();
C# 6
Null-Conditional Operator
Delegate Invocation
var handler = PropertyChanged;
if (handler != null)
{
handler(this, args);
}
Null-Conditional Operator
Delegate Invocation
PropertyChanged?.Invoke(this, args);
C# 6
String Interpolation
string.Format("{0} is {1} year{{s}} old.", p.Name, p.Age)
String Interpolation
$"{p.Name} tem {p.Age} ano{{s}}."
$"{p.Name,20} tem {p.Age:D3} ano{{s}}."
$"{p.Name} tem {p.Age} ano{(p.Age == 1 ? "" : "s")}."
C# 6
String Interpolation
Formattable Strings
IFormattable christmas = $"{new DateTime(2015, 12, 25):f}";
var christamasText =
christmas.ToString(string.Empty, new CultureInfo("pt-PT"));
C# 6
String Interpolation
Formattable Strings
FormattableStringFactory.Create("{0:f}", new DateTime(2015, 12, 25))
public abstract class FormattableString : IFormattable
{
protected FormattableString();
public abstract int ArgumentCount { get; }
public abstract string Format { get; }
public static string Invariant(FormattableString formattable);
public abstract object GetArgument(int index);
public abstract object[] GetArguments();
public override string ToString();
public abstract string ToString(IFormatProvider formatProvider);
}
.NET 4.6 or highier
C# 6
String Interpolation
Formattable Strings
FormattableString christmas = $"{new DateTime(2015, 12, 25):f}";
var christamasText = christmas.ToString(new CultureInfo("pt-PT"));
C# 6
String Interpolation
Formattable Strings
public static IDbCommand CreateCommand(
this IDbConnection connection,
FormattableString commandText)
{
var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
if (commandText.ArgumentCount > 0)
{
var commandTextArguments = new string[commandText.ArgumentCount];
for (var i = 0; i < commandText.ArgumentCount; i++)
{
commandTextArguments[i] = "@p" + i.ToString();
var p = command.CreateParameter();
p.ParameterName = commandTextArguments[i];
p.Value = commandText.GetArgument(i);
command.Parameters.Add(p);
}
command.CommandText = string.Format(CultureInfo.InvariantCulture,
commandText.Format,
commandTextArguments);
}
else
{
command.CommandText = commandText.Format;
}
return command;
}
var id = 10;
var nome = "Luis";
IDbConnection cnn = new SqlConnection();
var cmd = cnn.CreateCommand(
$"insert into test (id, nome) values({id}, {nome})");
cmd.ExecuteNonQuery();
C# 6
'nameof' Expressions
void M1(string x)
{
if (x == null) throw new ArgumentNullException("x");
var s = "ZipCode";
}
'nameof' Expressions
void M1(string x)
{
if (x == null) throw new ArgumentNullException(nameof(x));
var s = nameof(Person.Address.ZipCode);
}
C# 6
'nameof' Expressions
Source Code vs. Metadata
using S = System.String;
void M<T>(S s)
{
var s1 = nameof(T);
var s2 = nameof(S);
}
using S = System.String;
void M<T>(S s)
{
var s1 = "T";
var s2 = "S";
}
C# 6
Collection Initializers
'Add' Extension Methods
public class C<T> : IEnumerable<T>
{
// ...
}
public static class Cx
{
public static void Add<T>(this C<T> c, T i)
{
// ...
}
}
var cs = new C<int>();
cs.Add(1);
cs.Add(2);
cs.Add(3);
Collection Initializers
'Add' Extension Methods
public class C<T> : IEnumerable<T>
{
// ...
}
public static class Cx
{
public static void Add<T>(this C<T> c, T i)
{
// ...
}
}
var cs = new C<int> { 1, 2, 3 };
C# 6
Index Initializers
var numbers = new Dictionary<int, string>();
numbers[7] = "sete";
numbers[9] = "nove";
numbers[13] = "treze";
Index Initializers
var numbers = new Dictionary<int, string>
{
[7] = "sete",
[9] = "nove",
[13] = "treze"
};
C# 6
Exception Filters
try
{
//...
}
catch (SqlException ex) when (ex.Number == 2)
{
// ...
}
catch (SqlException ex)
{
// ...
}
Exectued in the context of
the throw, not the catch.
C# 6
'await' in 'catch' and 'finally' blocks
async Task M()
{
Resource res = null;
Exception ex = null;
try
{
res = await Resource.OpenAsync();
}
catch (ResourceException e)
{
ex = e;
}
if (ex != null) await Resource.LogAsync(res, e);
if (res != null) await res.CloseAsync();
}
'await' in 'catch' and 'finally' blocks
async Task M()
{
Resource res = null;
try
{
res = await Resource.OpenAsync();
}
catch (ResourceException e)
{
await Resource.LogAsync(res, e);
}
finally
{
if (res != null) await res.CloseAsync();
}
}
C# 6
C# Interactive
C# 6
Citação...
“.NET é bom, e Java é ruim...”
<Nome do Autor>
Referências
dotnet/roslyn, New Language Features in C# 6
– https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6
simple talk, What's New in C# 6
– https://www.simple-talk.com/dotnet/.net-framework/whats-new-in-c-6/
Revista PROGRAMAR, As Novidades Do C# 6
– http://www.revista-programar.info/artigos/as-novidades-do-c-sharp-6/
Obrigado!
Paulo Morgado
http://PauloMorgado.NET/
https://twitter.com/PauloMorgado
http://netponto.org/membro/paulo-morgado/
https://www.facebook.com/paulo.morgado
https://www.linkedin.com/in/PauloMorgado
http://www.revista-programar.info/author/pmorgado/
https://www.simple-talk.com/author/paulo-morgado/
http://www.slideshare.net/PauloJorgeMorgado
https://docs.com/paulo-morgado
Próximas reuniões presenciais
23/01/2016 – Janeiro – Lisboa
20/02/2016 – Fevereiro – Braga
27/02/2016 – Fevereiro – Lisboa
19/03/2016 – Março – Lisboa
26/03/2016 – Março – Porto
Reserva estes dias na agenda! :)
Patrocinadores “GOLD”
Patrocinadores “Silver”
Patrocinadores “Bronze”
http://bit.ly/netponto-aval-po-9
* Para quem não puder preencher durante a reunião,
iremos enviar um email com o link à tarde

More Related Content

PPSX
Tuga it 2016 - What's New In C# 6
PPSX
What's New In C# 7
PDF
PPSX
Tuga IT 2017 - What's new in C# 7
PPTX
C# 7.0 Hacks and Features
PDF
Java Class Design
PDF
Design Patterns - Compiler Case Study - Hands-on Examples
PPTX
Scala - where objects and functions meet
Tuga it 2016 - What's New In C# 6
What's New In C# 7
Tuga IT 2017 - What's new in C# 7
C# 7.0 Hacks and Features
Java Class Design
Design Patterns - Compiler Case Study - Hands-on Examples
Scala - where objects and functions meet

What's hot (20)

PDF
Python Performance 101
PPTX
Java 7, 8 & 9 - Moving the language forward
PDF
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
PPT
Profiling and optimization
PDF
Hammurabi
PPT
Euro python2011 High Performance Python
PDF
Haskell in the Real World
PPTX
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
PDF
Scala vs Java 8 in a Java 8 World
PDF
Odessapy2013 - Graph databases and Python
PPTX
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
PDF
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
PPT
Functional Programming In Java
PDF
JAVA 8 : Migration et enjeux stratégiques en entreprise
PDF
Coding Guidelines - Crafting Clean Code
PDF
Java Generics - by Example
PDF
Fun never stops. introduction to haskell programming language
PPTX
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
PDF
Functional programming in java
PPT
Collection Core Concept
Python Performance 101
Java 7, 8 & 9 - Moving the language forward
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Profiling and optimization
Hammurabi
Euro python2011 High Performance Python
Haskell in the Real World
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
Scala vs Java 8 in a Java 8 World
Odessapy2013 - Graph databases and Python
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Functional Programming In Java
JAVA 8 : Migration et enjeux stratégiques en entreprise
Coding Guidelines - Crafting Clean Code
Java Generics - by Example
Fun never stops. introduction to haskell programming language
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Functional programming in java
Collection Core Concept
Ad

Similar to What's new in C# 6 - NetPonto Porto 20160116 (20)

DOCX
Dotnet 18
PPSX
C# 6.0 - April 2014 preview
PDF
Дмитрий Верескун «Синтаксический сахар C#»
PPT
Linq intro
PPT
PostThis
PDF
Java and j2ee_lab-manual
ODP
Scala introduction
PPT
TechTalk - Dotnet
PDF
Clean up your code with C#6
PPT
Initial Java Core Concept
PPT
An imperative study of c
PPTX
Linq Sanjay Vyas
PPTX
Best of build 2021 - C# 10 & .NET 6
PDF
Bind me if you can
PDF
Java 8 new features or the ones you might actually use
PPT
Whats new in_csharp4
PPTX
C# 6.0
PPTX
Roslyn and C# 6.0 New Features
PPTX
Working effectively with legacy code
Dotnet 18
C# 6.0 - April 2014 preview
Дмитрий Верескун «Синтаксический сахар C#»
Linq intro
PostThis
Java and j2ee_lab-manual
Scala introduction
TechTalk - Dotnet
Clean up your code with C#6
Initial Java Core Concept
An imperative study of c
Linq Sanjay Vyas
Best of build 2021 - C# 10 & .NET 6
Bind me if you can
Java 8 new features or the ones you might actually use
Whats new in_csharp4
C# 6.0
Roslyn and C# 6.0 New Features
Working effectively with legacy code
Ad

More from Paulo Morgado (12)

PPTX
NetPonto - The Future Of C# - NetConf Edition
PPTX
Tuga IT 2018 Summer Edition - The Future of C#
PPSX
await Xamarin @ PTXug
PPSX
MVP Showcase 2015 - C#
PPSX
Roslyn analyzers: File->New->Project
PPSX
Async-await best practices in 10 minutes
PPSX
What’s New In C# 5.0 - iseltech'13
PPSX
What's New In C# 5.0 - Programar 2013
PPSX
What's new in c# 5.0 net ponto
PPTX
What's New In C# 5.0 - Rumos InsideOut
PPTX
Whats New In C# 4 0 - NetPonto
PPTX
As Novidades Do C# 4.0 - NetPonto
NetPonto - The Future Of C# - NetConf Edition
Tuga IT 2018 Summer Edition - The Future of C#
await Xamarin @ PTXug
MVP Showcase 2015 - C#
Roslyn analyzers: File->New->Project
Async-await best practices in 10 minutes
What’s New In C# 5.0 - iseltech'13
What's New In C# 5.0 - Programar 2013
What's new in c# 5.0 net ponto
What's New In C# 5.0 - Rumos InsideOut
Whats New In C# 4 0 - NetPonto
As Novidades Do C# 4.0 - NetPonto

Recently uploaded (20)

PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Nekopoi APK 2025 free lastest update
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
L1 - Introduction to python Backend.pptx
PDF
System and Network Administration Chapter 2
PDF
top salesforce developer skills in 2025.pdf
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Essential Infomation Tech presentation.pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
CHAPTER 2 - PM Management and IT Context
How Creative Agencies Leverage Project Management Software.pdf
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Odoo Companies in India – Driving Business Transformation.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Which alternative to Crystal Reports is best for small or large businesses.pdf
Softaken Excel to vCard Converter Software.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Nekopoi APK 2025 free lastest update
PTS Company Brochure 2025 (1).pdf.......
L1 - Introduction to python Backend.pptx
System and Network Administration Chapter 2
top salesforce developer skills in 2025.pdf
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
2025 Textile ERP Trends: SAP, Odoo & Oracle
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Essential Infomation Tech presentation.pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf

What's new in C# 6 - NetPonto Porto 20160116

Editor's Notes

  • #42: Estes patrocinadores oferecem goodies
  • #43: Survs ajuda com os inqueritos e Nucleo de Estudantes de Informática do ISEP que nos ajudaram e apoiaram na divulgação e na organização
  • #44: Para quem puder ir preenchendo, assim não chateio mais logo  É importante para recebermos nós feedback, e para darmos feedback aos nossos oradores http://goqr.me/