What is new in the new version 6.0 of the C# programming language? Telerik Academy Plus C# 6.0 and Roslyn Seminar.

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Coding JavaScript the expressive way Learning & Development Telerik Software Academy.
Asynchronous Programming with C# and WinRT
Unleash the Power of JavaScript Tooling Telerik Software Academy End-to-end JavaScript Applications.
Touch and Gestures with Xamarin Forms
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
With Mocha and Karma Telerik Academy Telerik Software Academy.
C# Fundamentals – Part I
Telerik Software Academy Telerik School Academy Creating E/R Diagrams with SQL Server.
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Optimization problems, Greedy Algorithms, Optimal Substructure and Greedy choice Learning & Development Team Telerik Software.
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Handling Errors during the Program Execution Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Telerik Software Academy End-to-end JavaScript Applications.
What is a Database, MySQL Specifics Trần Anh Tuấn Edit from Telerik Software Academy
General and reusable solutions to common problems in software design Vasil Dininski Telerik Software Academy academy.telerik.com Intern at Telerik Academy.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Building Rock-Solid Software Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Telerik Software Academy Databases.
Integer, Floating-Point, Text Data, Variables, Literals Telerik Corporation
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Definition, Constructors, Methods, Access Modifiers, Static/Instance members, Learning & Development Team Telerik Software Academy.
Presentation transcript:

What is new in the new version 6.0 of the C# programming language? Telerik Academy Plus C# 6.0 and Roslyn Seminar

 Windows 10 (Tech Preview)  Visual Studio "14" CTP 4  Roslyn Syntax Visualizer  ILSpy for decompiling the compiled code  Documentation and Roslyn source code   Demo code available in GitHub:  github.com/NikolayIT/CSharp-6-New-Features github.com/NikolayIT/CSharp-6-New-Features 2

3 C# 1.0 VS 2002.NET 1.0 Managed Code C# 2.0 VS 2005.NET 2.0 Generics Generics ReflectionReflection Anonymous Methods Partial Class Nullable Types C# 3.0 VS 2008.NET 3.5 Lambda Expression LINQLINQ Anonymous Types Extension Methods Implicit Type (var) C# 4.0 VS 2010.NET 4.0 dynamicdynamic Named Arguments Optional Parameters More COM Support C# 5.0 VS 2012.NET 4.5 Async / Await Caller Information C# 6.0 VS 14.NET ? A lot of new features….NET Compiler Platform (Roslyn)

 What is new in C# 6.0?  Auto-property Enhancements  Primary Constructors (dropped)  Expressions as Function Body  Using Static  Exception Filters  Declaration Expressions (inline declarations)  Nameof Expressions  Null-conditional Operators  Index Initializers  Await in catch/finally  Not Implemented, Yet 4

 You can add an initializer to an auto-property, just as you can to a field:  The initializer directly initializes the backing field  Just like field initializers, auto-property initializers cannot reference "this" 6 public class Person { public string FirstName { get; set; } = "Nikolay"; public string FirstName { get; set; } = "Nikolay"; public string LastName { get; set; } = "Kostov"; public string LastName { get; set; } = "Kostov";} this. k__BackingField = "Nikolay";

 Auto-properties can now be declared without a setter:  The backing field of a getter-only auto- property is implicitly declared as read-only:  It can be assigned to via property initializer  In future releases it will be possible to assign it in the declaring type’s constructor body public string FirstName { get; } = "Nikolay";.field private initonly string ' k__BackingField' 7

Allow constructor parameters to be declared directly on the class or struct, without an explicit constructor declaration in the body of the type declaration

 Some of the features currently only work when the LangVersion of the compiler is set to “experimental”  Adding the following line to the csproj file in appropriate places (e.g. next to ) will do the trick: <LangVersion>experimental</LangVersion> <PropertyGroup> experimental experimental 9

 With primary constructor (C# 6.0)  Without primary constructor (C# 5.0) public class Person(string firstName, string lastName) { public string FirstName { get; set; } = firstName; public string FirstName { get; set; } = firstName; public string LastName { get; set; } = lastName; public string LastName { get; set; } = lastName;} public class Person { private string firstName; private string firstName; private string lastName; private string lastName; public Person(string first, string last) { public Person(string first, string last) { firstName = first; firstName = first; lastName = last; lastName = last; } public string FirstName { get { return firstName; } } public string FirstName { get { return firstName; } } public string LastName { get { return lastName; } } } public string LastName { get { return lastName; } } } 10

 Sometimes there is a desire to do other things in constructor bodies, such as validate the constructor arguments: 11 public class Person(string firstName, string lastName) { { if (firstName == null) throw new ArgumentNullException("firstName"); if (firstName == null) throw new ArgumentNullException("firstName"); if (lastName == null) throw new ArgumentNullException("lastName"); if (lastName == null) throw new ArgumentNullException("lastName"); } public string FirstName { get; } = firstName; public string FirstName { get; } = firstName; public string LastName { get; } = lastName; public string LastName { get; } = lastName;}

 A class declaration with a primary constructor can still define other constructors  To ensure that arguments actually get passed to the primary constructor, all other constructors must call a this(…) initializer  The primary constructor is the only one that can call a base(…) initializer 12 public Person() : this ("Nikolay", "Kostov") { } : this ("Nikolay", "Kostov") { }

 The primary constructor always implicitly or explicitly calls a base initializer  If no base initializer is specified, it will default to calling a parameterless base constructor  The way to explicitly call the base initializer is to pass an argument list to a base class specifier 13 public class BufferFullException() : Exception("Buffer full") {}

Lambda expressions can be declared with an expression body as well as a conventional function body consisting of a block

 Methods as well as user-defined operators and conversions can be given an expression body by use of the “lambda arrow”:  The effect is exactly the same as if the methods had had a block body with a single return statement  For void returning methods - expression following the arrow must be a statement 15 public object Clone() => new Point(this.X, this.Y); public static Complex operator +(Complex a, Complex b) => a.Add(b);

 Expression bodies can be used to write getter- only properties and indexers where the body of the getter is given by the expression body  Note that there is no get keyword  It is implied by the use of the expression body syntax 16 public Person this[string name] => this.Children.FirstOrDefault( x => x.Name.Contains(name)); this.Children.FirstOrDefault( x => x.Name.Contains(name)); public string Name => FirstName + " " + LastName;

 Allows specifying a static class in a using clause  All its accessible static members become available without qualification 18 using System.Console; using System.Math; class Program { static void Main() static void Main() { WriteLine(Pow(2, 10)); WriteLine(Pow(2, 10)); }}

 If the parenthesized expression evaluates to true, the catch block is run  Already available in VB.NET and F# 20 try{ person = new Person("Nikolay", null); person = new Person("Nikolay", null);} catch(ArgumentNullException e) if(e.ParamName=="firstName") { Console.WriteLine("First name is null"); Console.WriteLine("First name is null");} catch(ArgumentNullException e) if(e.ParamName=="lastName") { Console.WriteLine("Last name is null"); Console.WriteLine("Last name is null");}

 We can use exception filters for side effects (e.g. logging)  Exception filters are preferable to catching and rethrowing (they leave the stack unharmed)  You have access to the actual stack when the exception araises 21 try {... } catch (Exception ex) if (Log(ex)) {... } private static bool Log(Exception exception) { Console.WriteLine(exception.Message); Console.WriteLine(exception.Message); return false; return false;}

Inline variable declarations. Experimental feature. Currently suspended.

 Declaration expressions allow you to declare local variables in the middle of an expression, with or without an initializer  The scope of the variables is to the nearest block or embedded statement (if-else) 23 if (int.TryParse(s, out int i)) {... } Console.WriteLine("Result: {0}", (var x = GetValue()) * x); if ((string str = obj as string) != null) {... str... } from s in strings select int.TryParse(s, out int i) ? i : -1;

 Occasionally you need to provide a string that names some program element  When throwing ArgumentNullException  When raising a PropertyChanged event  When selecting controller name in MVC  nameof() = Compiler checks, navigation, easy for renaming (refactoring)  Still missing support for other classes [info] info 25 if (x == null) throw new up",nameof(UserController),"SignUp")

Null-propagating operator ?.

 Lets you access members and elements only when the receiver is not-null  Providing a null result otherwise  Can be used together with the null coalescing operator ??:  Can also be chained 27 int? length = customers?.Length; //null if customers is null Customer first = customers?[0]; //null if customers is null int length = customers?.Length ?? 0; // 0 if customers null int? first = customers?[0].Orders?.Count();

 A new syntax to object initializers allowing to set values to keys through the indexers  Before (C# 5.0)  Now (C# 6.0) 29 var numbers = new Dictionary { [7] = "seven", [9] = "nine", [13] = "thirteen" }; var numbers = new Dictionary { { 7, "seven" }, { 7, "seven" }, { 9, "nine" }, { 9, "nine" }, { 13, "thirteen" } { 13, "thirteen" }};

 In C# 5.0 using the await keyword in catch and finally blocks was not allowed  This has actually been a significant limitation  In C# 6.0 await is now allowed in catch/finally 31 var input = new StreamReader(fileName); var log = new StreamWriter(logFileName); try { var line = await input.ReadLineAsync(); var line = await input.ReadLineAsync();} catch (IOException ex) { await log.WriteLineAsync(ex.ToString()); await log.WriteLineAsync(ex.ToString());} finally { if (log != null) await log.FlushAsync(); if (log != null) await log.FlushAsync();}

Not implemented C# features as of October 2014

 Binary literals and digit separators  private protected – for derives in the assembly 33 var bits = 0b ; var hex = 0x00_2E; var dec = 1_234_567_890; protected internal privateprotected private protected protected internal privatepublic

 Indexed member initializer  Indexed member access  Equivalent to 34 var obj = new JObject { $first = "N", $last = "K" } // Equivalent to var obj = new JObject(); obj["first"] = "N"; obj["last"] = "K"; obj.$name = obj.$first + " " + obj.$last; obj["name"] = obj["first"] + " " + obj["last"];

 Params IEnumerable<>  Event initializers  Constructor Inference  Instead of 35 decimal Avg(params IEnumerable numbers) { … } var tuple = new Tuple(3, "three", true); var fsw = new FileSystemWatcher { Changed += FswCh };

 Semicolon operator  String interpolation  This feature is planned and probably will be released in the next CTP (5) of VS 14  More information: [link] link  Constructor assignment to getter-only auto- properties 36 var res = (var x = 4; Console.Write(x); x * x); // 16 var str = $"{hello}, {world}!"; // Instead of var str = string.Format("{0}, {1}!", hello, world); int P { get; } public Class() { P = 15; }

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране