C# 6
Pascal Laurin
November 2015
@plaurin78
pascal.laurin@outlook.com
www.pascallaurin.com
http://fr.slideshare.net/PascalLaurin
https://bitbucket.org/pascallaurin
Microsoft .NET MVP
Developer & Architect at GSoft
A brief history of C#
What’s new in C# 6
C# vNext
Agenda
Created by a team lead by Anders Hejlsberg
Inspiration from Pascal and Delphi
Now working on TypeScript
C# 1: The beginning [2002]
Ref: https://en.wikipedia.org/wiki/Anders_Hejlsberg
Generics
Anonymous Methods
Nullable Type
Partial Class
Iterators
C# 2 : Generics [2005]
new Dictionary<int, string>();
delegate() { Console.WriteLine("Hello"); }
int? a = null;
if (a.HasValue) { }
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
public static IEnumerable<int> Generate()
{
foreach (var item in Enumerable.Repeat(5, 5))
yield return item * 2;
}
C# .NET Framework CLR Visual Studio
1 1.0 1.0 .NET
1 1.1 1.1 2003
2 2.0 2.0 2005
2 3.0 2.0 -
3 3.5 2.0 2008
4 4.0 4.0 2010
5 4.5 4.0 2012
- 4.5.1 4.0 2013
6 4.6 4.0 2015
Interlude :
C# vs .NET Framework vs CLR vs Visual
Studio
Ref: https://msdn.microsoft.com/en-us/library/bb822049(v=vs.110).aspx
Implicit Type (var)
Object and Collection Initializers
Auto-Implemented Properties
Lambda Expression
C# 3 : LINQ [2008]
var result = data.Where(x => x % 2 == 0);
var data = new[] { 1, 2, 3 };
var entity = new Entity { Name = "Pascal" };
internal class Entity
{
public string Name { get; set; }
}
LINQ
Anonymous Types
Extension Method
Expression Tree
C# 3 : LINQ [2008]
A.CallTo(() => repository.GetEntityById(idEntity))
.Returns(fakeEntity);
var result = data.Select(x => new
{
Name = x.ToString(),
Value = x
});
public static class Enumerable
{
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
...
}
}
https://www.linqpad.net/
C# scratch pad
100+ samples on LINQ, F#, Async, RX
https://code.visualstudio.com/
Cross platform editor
http://csharppad.com/
Online editor
http://scriptcs.net/
C# scripting
http://pexforfun.com/
Mastermind game in C#
Interlude :
Editors and tools
Dynamic
Named Arguments
Optional Parameters
C# 4 : Dynamic [2010]
dynamic d = entity;
d.CallMethod("Foo");
entity.CallMethod(value: 42, name: "Pascal");
public void CallMethod(string name, int value = 0) { }
Async Feature
Caller Information
C# 5 : Async [2012]
private async Task Do()
{
var client = new HttpClient();
var result = await client.GetAsync("http://www.google.com");
}
public void CallMethod([CallerFilePath] string filePath = "Unknown",
[CallerMemberName] string memberName = "Unknown",
[CallerLineNumber] int line = -1)
{
}
What is a compiler?
Interlude :
What is Roslyn?
Code Compiler Executable
Compiler As A Service
Interlude :
What is Roslyn?
Expression-level features
Nameof
String interpolation
Null-conditional operators (Elvis operator)
Index initializers
Statement-level features
Exception filters
Await in catch and finally blocks
Member declaration features
Auto-properties initializers
Getter-only auto-properties
Expression-bodied function members
Import features
Using static
Demos!!
C# 6 : Developer productivity [2015]
Nameof
String interpolation
Expression-level features
var dog = new Dog();
Console.WriteLine(
$"My dog {dog.Name,10} is {dog.Age} year{(dog.Age > 1 ? "s" : "")} old");
public static class NameOf
{
public static void MyMethod(string message)
{
if (message == null) throw new ArgumentNullException(nameof(message));
Console.WriteLine(nameof(message));
Console.WriteLine(
nameof(MyApp.Namespace.Demos) + nameof(NameOf) + nameof(MyMethod));
const int foo = 42;
Console.WriteLine(nameof(foo));
}
Null-conditional operators (Elvis operator)
Index initializers
Expression-level features
order?.Items?.Count;
order?.Items?[0].Name;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
var j = new JObject
{
["firstName"] = "Pascal",
["lastName"] = "Laurin«
};
Exception filters
Await in catch and finally blocks
Statement-level features
catch (Exception e) when (e.Message == "Foo")
{
Console.WriteLine("Was Foo");
}
catch (Exception)
{
var catchResult = await client.GetAsync("http://www.catch.com");
Console.WriteLine($"Catch: {catchResult.StatusCode}");
}
finally
{
var finallyResult = await client.GetAsync("http://www.finally.com");
Console.WriteLine($"Finally: {finallyResult.StatusCode}");
}
Auto-properties initializers
Getter-only auto-properties
Expression-bodied function members
Member declaration features
public string First { get; private set; } = "Pascal";
public string Last { get; private set; } = "Laurin";
public string First { get; } = "Pascal";
public string Last { get; } = "Laurin";
public int SomeFct(int a, int b) => a * b + a;
public string GetFullName() => $"{First} {Last}";
public void Print() => Console.WriteLine(GetFullName());
public string this[long id] => (id * 2).ToString();
Xamarin Studio “Roslyn” Preview Release
https://developer.xamarin.com/guides/cross-platform/xamarin-
studio/
Interlude :
Mono and Xamarin?
Outline of C# 7 demo at MVP Summit 2015-11-02
https://github.com/dotnet/roslyn/issues/6505
C# 7 Work List of Features
https://github.com/dotnet/roslyn/issues/2136
Design Notes
https://github.com/dotnet/roslyn/labels/Design%20Notes
Area-Language Design
https://github.com/dotnet/roslyn/labels/Area-Language%20Design
C# 7 and beyond
21
Local functions
static void Main(string[] args)
{
int Fib(int n) => (n < 2) ? 1 : Fib(n - 1) + Fib(n - 2); //!
Console.WriteLine(Fib(7));
Console.ReadKey();
}
static void Main(string[] args)
{
int fib0 = 1; //!
int Fib(int n) => (n < 2) ? fib0 : Fib(n - 1) + Fib(n - 2);
Console.WriteLine(Fib(7));
Console.ReadKey();
}
22
Records
// class Person(string Name);
class Person
{
public Person(string name) { this.Name = name; }
public string Name { get; }
}
// class Student(string Name, double Gpa) : Person(Name);
class Student : Person
{
public Student(string name, double gpa) : base(name) { this.Gpa = gpa; }
public double Gpa { get; }
}
// class Teacher(string Name, string Subject) : Person(Name);
class Teacher : Person
{
public Teacher(string name, string subject) : base(name)
{
this.Subject = subject;
}
public string Subject { get; }
}
23
Patterns matching
static string PrintedForm(Person p)
{
if (p is Student s && s.Gpa > 3.5) //!
{
return $"Honor Student {s.Name} ({s.Gpa})";
}
else if (p is Student s)
{
return $"Student {s.Name} ({s.Gpa})";
}
else if (p is Teacher t)
{
return $"Teacher {t.Name} of {t.Subject}";
}
else
{
return $"Person {p.Name}";
}
}
24
match expression and when clause
return p match ( //!
case Student s when s.Gpa > 3.5 : //!
$"Honor Student {s.Name} ({s.Gpa})"
case Student { Name is "Poindexter" } : //!
"A Nerd"
case Student s :
$"Student {s.Name} ({s.Gpa})"
case Teacher t :
$"Teacher {t.Name} of {t.Subject}"
case null : //!
throw new ArgumentNullException(nameof(p))
case * : //!
$"Person {p.Name}"
);
Language Features in C# 6
https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-
C%23-6
7 minutes video on C# 6
https://channel9.msdn.com/Series/ConnectOn-Demand/211
Questions?
References
@plaurin78
pascal.laurin@outlook.com
www.pascallaurin.com
http://fr.slideshare.net/PascalLaurin
https://bitbucket.org/pascallaurin/csharp6-talk

C# 6

  • 1.
    C# 6 Pascal Laurin November2015 @plaurin78 pascal.laurin@outlook.com www.pascallaurin.com http://fr.slideshare.net/PascalLaurin https://bitbucket.org/pascallaurin Microsoft .NET MVP Developer & Architect at GSoft
  • 2.
    A brief historyof C# What’s new in C# 6 C# vNext Agenda
  • 3.
    Created by ateam lead by Anders Hejlsberg Inspiration from Pascal and Delphi Now working on TypeScript C# 1: The beginning [2002] Ref: https://en.wikipedia.org/wiki/Anders_Hejlsberg
  • 4.
    Generics Anonymous Methods Nullable Type PartialClass Iterators C# 2 : Generics [2005] new Dictionary<int, string>(); delegate() { Console.WriteLine("Hello"); } int? a = null; if (a.HasValue) { } public partial class Form1 : Form { public Form1() { InitializeComponent(); } } public static IEnumerable<int> Generate() { foreach (var item in Enumerable.Repeat(5, 5)) yield return item * 2; }
  • 5.
    C# .NET FrameworkCLR Visual Studio 1 1.0 1.0 .NET 1 1.1 1.1 2003 2 2.0 2.0 2005 2 3.0 2.0 - 3 3.5 2.0 2008 4 4.0 4.0 2010 5 4.5 4.0 2012 - 4.5.1 4.0 2013 6 4.6 4.0 2015 Interlude : C# vs .NET Framework vs CLR vs Visual Studio Ref: https://msdn.microsoft.com/en-us/library/bb822049(v=vs.110).aspx
  • 6.
    Implicit Type (var) Objectand Collection Initializers Auto-Implemented Properties Lambda Expression C# 3 : LINQ [2008] var result = data.Where(x => x % 2 == 0); var data = new[] { 1, 2, 3 }; var entity = new Entity { Name = "Pascal" }; internal class Entity { public string Name { get; set; } }
  • 7.
    LINQ Anonymous Types Extension Method ExpressionTree C# 3 : LINQ [2008] A.CallTo(() => repository.GetEntityById(idEntity)) .Returns(fakeEntity); var result = data.Select(x => new { Name = x.ToString(), Value = x }); public static class Enumerable { public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { ... } }
  • 8.
    https://www.linqpad.net/ C# scratch pad 100+samples on LINQ, F#, Async, RX https://code.visualstudio.com/ Cross platform editor http://csharppad.com/ Online editor http://scriptcs.net/ C# scripting http://pexforfun.com/ Mastermind game in C# Interlude : Editors and tools
  • 9.
    Dynamic Named Arguments Optional Parameters C#4 : Dynamic [2010] dynamic d = entity; d.CallMethod("Foo"); entity.CallMethod(value: 42, name: "Pascal"); public void CallMethod(string name, int value = 0) { }
  • 10.
    Async Feature Caller Information C#5 : Async [2012] private async Task Do() { var client = new HttpClient(); var result = await client.GetAsync("http://www.google.com"); } public void CallMethod([CallerFilePath] string filePath = "Unknown", [CallerMemberName] string memberName = "Unknown", [CallerLineNumber] int line = -1) { }
  • 11.
    What is acompiler? Interlude : What is Roslyn? Code Compiler Executable
  • 12.
    Compiler As AService Interlude : What is Roslyn?
  • 13.
    Expression-level features Nameof String interpolation Null-conditionaloperators (Elvis operator) Index initializers Statement-level features Exception filters Await in catch and finally blocks Member declaration features Auto-properties initializers Getter-only auto-properties Expression-bodied function members Import features Using static Demos!! C# 6 : Developer productivity [2015]
  • 14.
    Nameof String interpolation Expression-level features vardog = new Dog(); Console.WriteLine( $"My dog {dog.Name,10} is {dog.Age} year{(dog.Age > 1 ? "s" : "")} old"); public static class NameOf { public static void MyMethod(string message) { if (message == null) throw new ArgumentNullException(nameof(message)); Console.WriteLine(nameof(message)); Console.WriteLine( nameof(MyApp.Namespace.Demos) + nameof(NameOf) + nameof(MyMethod)); const int foo = 42; Console.WriteLine(nameof(foo)); }
  • 15.
    Null-conditional operators (Elvisoperator) Index initializers Expression-level features order?.Items?.Count; order?.Items?[0].Name; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); var j = new JObject { ["firstName"] = "Pascal", ["lastName"] = "Laurin« };
  • 16.
    Exception filters Await incatch and finally blocks Statement-level features catch (Exception e) when (e.Message == "Foo") { Console.WriteLine("Was Foo"); } catch (Exception) { var catchResult = await client.GetAsync("http://www.catch.com"); Console.WriteLine($"Catch: {catchResult.StatusCode}"); } finally { var finallyResult = await client.GetAsync("http://www.finally.com"); Console.WriteLine($"Finally: {finallyResult.StatusCode}"); }
  • 17.
    Auto-properties initializers Getter-only auto-properties Expression-bodiedfunction members Member declaration features public string First { get; private set; } = "Pascal"; public string Last { get; private set; } = "Laurin"; public string First { get; } = "Pascal"; public string Last { get; } = "Laurin"; public int SomeFct(int a, int b) => a * b + a; public string GetFullName() => $"{First} {Last}"; public void Print() => Console.WriteLine(GetFullName()); public string this[long id] => (id * 2).ToString();
  • 18.
    Xamarin Studio “Roslyn”Preview Release https://developer.xamarin.com/guides/cross-platform/xamarin- studio/ Interlude : Mono and Xamarin?
  • 19.
    Outline of C#7 demo at MVP Summit 2015-11-02 https://github.com/dotnet/roslyn/issues/6505 C# 7 Work List of Features https://github.com/dotnet/roslyn/issues/2136 Design Notes https://github.com/dotnet/roslyn/labels/Design%20Notes Area-Language Design https://github.com/dotnet/roslyn/labels/Area-Language%20Design C# 7 and beyond
  • 20.
    21 Local functions static voidMain(string[] args) { int Fib(int n) => (n < 2) ? 1 : Fib(n - 1) + Fib(n - 2); //! Console.WriteLine(Fib(7)); Console.ReadKey(); } static void Main(string[] args) { int fib0 = 1; //! int Fib(int n) => (n < 2) ? fib0 : Fib(n - 1) + Fib(n - 2); Console.WriteLine(Fib(7)); Console.ReadKey(); }
  • 21.
    22 Records // class Person(stringName); class Person { public Person(string name) { this.Name = name; } public string Name { get; } } // class Student(string Name, double Gpa) : Person(Name); class Student : Person { public Student(string name, double gpa) : base(name) { this.Gpa = gpa; } public double Gpa { get; } } // class Teacher(string Name, string Subject) : Person(Name); class Teacher : Person { public Teacher(string name, string subject) : base(name) { this.Subject = subject; } public string Subject { get; } }
  • 22.
    23 Patterns matching static stringPrintedForm(Person p) { if (p is Student s && s.Gpa > 3.5) //! { return $"Honor Student {s.Name} ({s.Gpa})"; } else if (p is Student s) { return $"Student {s.Name} ({s.Gpa})"; } else if (p is Teacher t) { return $"Teacher {t.Name} of {t.Subject}"; } else { return $"Person {p.Name}"; } }
  • 23.
    24 match expression andwhen clause return p match ( //! case Student s when s.Gpa > 3.5 : //! $"Honor Student {s.Name} ({s.Gpa})" case Student { Name is "Poindexter" } : //! "A Nerd" case Student s : $"Student {s.Name} ({s.Gpa})" case Teacher t : $"Teacher {t.Name} of {t.Subject}" case null : //! throw new ArgumentNullException(nameof(p)) case * : //! $"Person {p.Name}" );
  • 24.
    Language Features inC# 6 https://github.com/dotnet/roslyn/wiki/New-Language-Features-in- C%23-6 7 minutes video on C# 6 https://channel9.msdn.com/Series/ConnectOn-Demand/211 Questions? References @plaurin78 pascal.laurin@outlook.com www.pascallaurin.com http://fr.slideshare.net/PascalLaurin https://bitbucket.org/pascallaurin/csharp6-talk