what is new in the new version 6.0 of the c# programming language? telerik academy plus c# 6.0 and...
TRANSCRIPT
What is New in C# 6.0?
What is new in the new version 6.0 of the C# programming language?
Telerik Academy Plushttp://academy.telerik.com
C# 6.0 and Roslyn Seminar
2
Used Software and Tools
Windows 10 (Tech Preview) Visual Studio "14" CTP 4
Roslyn Syntax Visualizer
ILSpy for decompiling thecompiled code
Documentation and Roslyn source code http://roslyn.codeplex.com/
Demo code available in GitHub: github.com/NikolayIT
/CSharp-6-New-Features
3
History of the C# Language
C# 1.0VS
2002.NET 1.0
Managed Code
C# 2.0VS
2005.NET 2.0
Generics<T>
Reflection
Anonymous
Methods
Partial Class
Nullable Types
C# 3.0VS
2008.NET 3.5
Lambda Expressi
onLINQ
Anonymous
Types
Extension
Methods
Implicit Type (var)
C# 4.0VS
2010.NET 4.0
dynamicNamed Argume
nts
Optional Paramet
ers
More COM
Support
C# 5.0VS
2012.NET 4.5
Async / Await
Caller Informati
on
C# 6.0 VS 14.NET ?
A lot of new features….NET Compiler
Platform (Roslyn)
4
Table of Contents 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
6
Initializers for Auto-Properties
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"
public class Person{ public string FirstName { get; set; } = "Nikolay"; public string LastName { get; set; } = "Kostov";}
this.<FirstName>k__BackingField = "Nikolay";
7
Getter-Only Auto-Properties
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 '<FirstName>k__BackingField'
Primary ConstructorsAllow constructor parameters to be declared directly on the class or struct,
without an explicit constructor declaration in the body of the type
declaration
Dropped
9
Experimental Features 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 <WarnLevel>) will do the trick:<LangVersion>experimental</LangVersion>
<PropertyGroup> ... <LangVersion>experimental</LangVersion> </PropertyGroup>
10
Parameters on Classes and Structs 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 LastName { get; set; } = lastName;}public class Person { private string firstName; private string lastName; public Person(string first, string last) { firstName = first; lastName = last; } public string FirstName { get { return firstName; } } public string LastName { get { return lastName; } }}
11
Primary Constructor Bodies
Sometimes there is a desire to do other things in constructor bodies, such as validate the constructor arguments:public class Person(string firstName, string lastName){ { if (firstName == null) throw new ArgumentNullException("firstName"); if (lastName == null) throw new ArgumentNullException("lastName"); } public string FirstName { get; } = firstName; public string LastName { get; } = lastName;}
12
Explicit Constructors 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
public Person() : this ("Nikolay", "Kostov") { }
13
Base Initializer 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
public class BufferFullException() : Exception("Buffer full"){}
Expression BodiedFunction Members
Lambda expressions can be declared with an expression body as well as a
conventional function body consisting of a block
15
Expression as Method Body
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
public object Clone() => new Point(this.X, this.Y);
public static Complex operator +(Complex a, Complex b) => a.Add(b);
16
Expression as Property Getter
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
public Person this[string name] => this.Children.FirstOrDefault( x => x.Name.Contains(name));
public string Name => FirstName + " " + LastName;
18
Using Static Allows specifying a static class in a using clause All its accessible static members
become available without qualificationusing System.Console;
using System.Math;class Program{ static void Main() { WriteLine(Pow(2, 10)); }}
20
Exception Filters If the parenthesized expression evaluates to true, the catch block is run
Already available in VB.NET and F#
try{ person = new Person("Nikolay", null);}catch(ArgumentNullException e) if(e.ParamName=="firstName"){ Console.WriteLine("First name is null");}catch(ArgumentNullException e) if(e.ParamName=="lastName"){ Console.WriteLine("Last name is null");}
21
Logging with Exception Filters
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
try { ... }catch (Exception ex) if (Log(ex)) { ... }
private static bool Log(Exception exception){ Console.WriteLine(exception.Message); return false;}
Declaration ExpressionsInline variable declarations.
Experimental feature. Currently suspended.
Dropped
23
Declaration Expressions 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)
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 stringsselect int.TryParse(s, out int i) ? i : -1;
25
Nameof Expressions 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]
if (x == null) throw new ArgumentNullException(nameof(x));
@Html.ActionLink("Sign up",nameof(UserController),"SignUp")
27
Null-conditional Operators
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
int? length = customers?.Length; //null if customers is nullCustomer first = customers?[0]; //null if customers is null
int length = customers?.Length ?? 0; // 0 if customers null
int? first = customers?[0].Orders?.Count();
Index Initializers 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<int, string> { [7] = "seven", [9] = "nine", [13] = "thirteen"};
var numbers = new Dictionary<int, string> { { 7, "seven" }, { 9, "nine" }, { 13, "thirteen" }};
Await in catch/finally 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();}catch (IOException ex) { await log.WriteLineAsync(ex.ToString());}finally { if (log != null) await log.FlushAsync();}
Not Implemented, Yet 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;
protectedinternalprivate protected
protected internal private public
Not Implemented, Yet (2)
Indexed member initializer
Indexed member access
Equivalent to
34
var obj = new JObject { $first = "N", $last = "K" }// Equivalent tovar obj = new JObject();obj["first"] = "N";obj["last"] = "K";
obj.$name = obj.$first + " " + obj.$last;
obj["name"] = obj["first"] + " " + obj["last"];
Not Implemented, Yet (3)
Params IEnumerable<>
Event initializers
Constructor Inference
Instead of
35
decimal Avg(params IEnumerable<int> numbers) { … }
var tuple = new Tuple(3, "three", true);
var tuple = new Tuple<int,string,bool>(3, "three", true);
var fsw = new FileSystemWatcher { Changed += FswCh };
Not Implemented, Yet (4)
Semicolon operator
String interpolation
This feature is planned and probably will be released in the next CTP (5) of VS 14
More information: [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 ofvar 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#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно
?
? ? ??
?? ?
?
?
?
??
?
?
? ?
Questions?
?
What is New in C# 6.0?
http://academy.telerik.com/seminars/software-engineering