Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "What is new in the new version 6.0 of the C# programming language? Telerik Academy Plus C# 6.0 and Roslyn Seminar."— Presentation transcript:

1 What is new in the new version 6.0 of the C# programming language? Telerik Academy Plus http://academy.telerik.com C# 6.0 and Roslyn Seminar

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

3 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)

4  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

5

6  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";

7  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

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

9  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

10  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

11  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;}

12  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") { }

13  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") {}

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

15  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);

16  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;

17

18  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)); }}

19

20  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");}

21  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;}

22 Inline variable declarations. Experimental feature. Currently suspended.

23  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;

24

25  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 ArgumentNullException(nameof(x)); @Html.ActionLink("Sign up",nameof(UserController),"SignUp")

26 Null-propagating operator ?.

27  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();

28

29  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" }};

30

31  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();}

32 Not implemented C# features as of October 2014

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

34  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"];

35  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 };

36  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; }

37 форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен 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# Николай Костов - блог за програмиране http://academy.telerik.com/seminars/software-engineering


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

Similar presentations


Ads by Google