C# 6 Peek into the future How to Simplify and Clarify your code
Tome Tomovski
Introduction
• Author– Microsoft Certified Trainer, Engineer, Consultant– Main fields: Banking, Telecommunication, Oil & Gas and Industrial IT
• “Failing is trying, trying is everything” …inspiring software developers to write better
code and be more productive
Is it a revolution?
• C# 2.0 and 3.0 (.NET 2.0/3.5)• Introduction to generics and a way to program collections
with LINQ• C# 4.0 (.NET 4.0)
• Named and Optional Parameters, Dynamic support, COM Interop
• C# 5.0 (.NET 4.5)• Simplification of asynchronous programming patterns
• C# 6.0 (.NET 4.6/5)• Simply changes the way we write C# code
Peek into C# 6.0 Features
• Auto property initialization• Dictionary initialization• String interpolation ($ sign)• Using Static syntax• nameof method• Exception filters• Lambda expression debugging• Async / await in error handling• Null conditional operator
New Features
Configure Build for language version
Auto Property Initialization
• Before:• If we had to provide default value for properties =>
initialize the properties in the constructor of that class.• Now:
– Auto property initializer /// Class using auto propery initialization public class Student { public int Id { get; set; } = 1; public string Name { get; set; } = "John"; public string Grade { get; set; } = "A++"; public DateTime JoiningDate { get; set; } = DateTime.UtcNow; }
public class Student { /// /// Default constructor to initialize /// properties public Student1() { this.Id = 1; this.Name = "John"; this.Grade = "A++"; this.JoiningDate = DateTime.Now.Date; } public int Id { get; set; } public string Name { get; set; } public string Grade { get; set; } public DateTime JoiningDate { get; set; } }
Dictionary Initialization
• Before:• Initializing Dictionary collection with double curly braces• Confusing for most C# developers
• Now:– New format which is much easier to read
Dictionary<int, string> students = new Dictionary<int, string>() { { 1, "Jane" }, { 2, "Marta" }, };
Dictionary<int, string> studentsNew = new Dictionary<int, string>() { [1] = "Jane", [2] = "Marta", };
String Interpolation ($ sign)
• Before:• Used placeholder {0}, {1}, and then replacing these
placeholder values with actual values
• Now:– Directly user variable or even expression instead of using
placeholders
string name = "Tome";string blogName = "MSDN";Console.WriteLine(String.Format("{0} is reading {1}", name, blogName));
/// Class using auto propery initialization Console.WriteLine($"{name} is reading {blogName}");
Using static syntax
• Before:• Had to put qualifying type name before accessing the
static member
• Now:– Import all static member of type (class)
Console.WriteLine(Math.Sqrt(3 * 3 + 4 * 4));Console.WriteLine(Math.Round(16.66));Console.WriteLine(Math.Pow(2, 3));
/// Add using static System.Console/// Add using static System.Marh/// Class using auto propery initialization WriteLine(Sqrt(3 * 3 + 4 * 4));WriteLine(Round(16.66));WriteLine(Pow(2, 3));
nameof Method
• Before:• … not existent
• Now:– To return the name of any program element– When we want to use the name of any programming
element to raise an event that uses name of some element.string firstName = "John Doe";Console.WriteLine(string.Format("Variable Name = {0}"), nameof(firstName));
Exception filter
• Now:– Enable conditional execution of catch block– Different catch block for each specific condition
try{
throw new Exception("Error");}catch (Exception ex) when (ex.Message == "ReallyBadError"){
// this one will not execute.}catch (Exception ex) when (ex.Message == "Error"){
// this one will executeWriteLine("This one will execute");
}
Async / await in error handling
• Now:– Await functionality in error
handling– If any operation performs
operation in try block then catch and finally block wait for the operation to be completed and then we may perform asynchronous operation in catch and finally block.
– Ex: Log exceptions in a DB without blocking the current thread.
try{
throw new Exception("Error");}catch (Exception ex) when (ex.Message == "ReallyBadError"){
// this one will not execute.}catch (Exception ex) when (ex.Message == "Error"){
// this one will executeWriteLine("This one will
execute");}
Lambda expression debugging
• Now:– Still under development– Expression debugging when working with LINQ and
lambda expressions– Native functions as LINQ-to-SQL still not supported
float[] values = Enumerable.Range(0, 100).Select(i => (float)i / 10).ToArray();
Add to watch windowvalues.Where(v => (int)v == 3).ToArray()
Universal Windows apps
Debugging and Diagnostics
• PerfTips• Display the execution time of methods during debugging• Quickly spot bottlenecks
• Error List– Supports filtering on any column– Live view of errors, warnings and code analysis
• GPU Usage Tool– Helps to troubleshoot whether performance bottlenecks
are originating in the CPU or GPU.
Live code analysis (light bulbs)
• New C# compiler• Rich and customizable feedback and suggestions
directly inside the code editor as you type.
Blend in and rock
• Blend for Visual Studio 2015 comes with several enhancements:• Basic Debugging Support• Peek in XAML• Custom Windows Layouts• Source Control• NuGet• XAML IntelliSense!
Application Insights
• Helps developers detect issues, diagnose crashes and track usage in their mobile and Web apps on Azure, IIS and J2EE
• Analytics solution that monitors the performance and usage of live applications
Code understanding
• Renaming improvements• Introduction of new quick actions to rename variables• Preview rename operations and expand rename
operations
Code understanding
• Renaming improvements• Introduction of new quick actions to rename variables• Preview rename operations and expand rename
operations