New Features of C# Kuppurasu Nagaraj Microsoft Connect 2016

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Review of C++ Programming Part II Sheng-Fang Huang.
CH1 – A 1 st Program Using C#. Program Set of instructions which tell a computer what to do. Machine Language Basic language computers use to control.
SE-1010 Dr. Mark L. Hornick 1 Defining Your Own Classes Part 3.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Introduction to Exception Handling and Defensive Programming.
Applied Computing Technology Laboratory QuickStart C# Learning to Program in C# Amy Roberge & John Linehan November 7, 2005.
ILM Proprietary and Confidential -
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
C# 2.0 and Future Directions Anders Hejlsberg Technical Fellow Microsoft Corporation.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Writing Better C# Using C# 6 By: Mitchel Sellers.
1 Statements © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License.
C# Present and Future Marita Paletsou Software Engineer.
C# 5.0 Alex Davies 22 nd December What we will cover C# 5.0,.NET 4.5, Visual Studio 11 Caller Info Attributes Upgrade from synchronous to asynchronous.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
C++ Lesson 1.
The need for Programming Languages
C# for C++ Programmers 1.
Basic Introduction to C#
Creating Your Own Classes
Chapter - 4 OOP with C# S. Nandagopalan.
Static data members Constructors and Destructors
BİL527 – Bilgisayar Programlama I
CIS 200 Test 01 Review.
Ch 10- Advanced Object-Oriented Programming Features
Advance OOP in PHP.
Lambda Expressions By Val Feldsher.
Representation, Syntax, Paradigms, Types
Why exception handling in C++?
Upgrading Your C# Programming Skills to Be a More Effective Developer
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Microsoft Ignite NZ October 2016 SKYCITY, Auckland.
New Features in C# 7.0 Mads Torgersen C# Program Manager
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
OOP’S Concepts in C#.Net
Understanding Inheritance
.NET and .NET Core 9. Towards Higher Order Pan Wuming 2017.
Lecture 3 Functions Simple functions
Pass by Reference, const, readonly, struct
Java Programming Language
Chapter 17 Templates and Exceptions Part 2
Conditional Statements
What’s new in F# 4.1 Phillip Carter Program Manager.
Representation, Syntax, Paradigms, Types
Constructors and Other Tools
Representation, Syntax, Paradigms, Types
CISC/CMPE320 - Prof. McLeod
Tonga Institute of Higher Education
Representation, Syntax, Paradigms, Types
Class.
Introduction to Programming
Class rational part2.
Corresponds with Chapter 5
CS 240 – Advanced Programming Concepts
Chengyu Sun California State University, Los Angeles
Presentation transcript:

New Features of C# 30.03.2017 Kuppurasu Nagaraj Microsoft Connect 2016 9/8/2018 11:06 PM New Features of C# 30.03.2017 Kuppurasu Nagaraj © 2016 Microsoft Corporation. All rights reserved. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

C# Features Highlights What is new in C# 1.0 Managed Code What is new in C# 2.0 Generics Partial types Anonymous methods Iterators Nullable types Getter/setter separate accessibility Method group conversions (delegates) Co- and Contra-variance for delegates Static classes Delegate inference What is new in C# 3.0 Implicitly typed local variables Object and collection initializers Auto-Implemented properties Anonymous types Extension methods Query expressions Lambda expressions Expression trees Partial Methods What is new in C# 4.0 Dynamic binding (late binding) Named and optional arguments Generic co- and contravariance Embedded interop types What is new in C# 5.0 Async features Caller information What is new in C# 6.0 Read-only Auto-properties Auto-Property Initializers Expression-bodied function members using static Null - conditional operators String Interpolation Exception filters nameof Expressions await in catch and finally blocks index initializers Extension methods for collection initializers Improved overload resolution What is new in C# 7.0 out variables Tuples Pattern Matching ref locals and returns Local Functions More expression-bodied members throw Expressions Generalized async return types Numeric literal syntax improvements

What is new in C# 5.0 What is new in C# 5.0 Async features Caller information

Async features Introduced in C# 5.0 and Target framework 4.5. This method can return before it has finished executing. Any method perform long running task, such as web resource or reading file. Especially important in graphical program. VS 2012 onwards support

Async features The async keyword marks a method for the compiler. The await keyword signals the code to wait for the return of a long running operation. Creating Asynchronous Methods There are three approaches to creating asynchronous methods using the new features; each being defined by its return type: Methods that return void Methods that return Task Methods that return Task<T> public static async void CalculateSumAsync(int i1, int i2) { int sum = await Task.Run(() => { return i1 + i2; }); Console.WriteLine("Value: {0}", sum); }

Rules for use The following are the rules for use: The await keyword may not be inserted into a "lock" code block With try-catch-finally blocks, await may not be used in the catch or finally sections Async methods may not use "ref" nor "out" parameters Class constructors may not be marked async nor may they use the await keyword Await may only be used in methods marked as async Property accessors may not be marked as async nor may they use await

Caller information Caller information gives information about the caller of any function. These three types of attributes that are used in tracking information. CallerFilePath: Sets the information about caller's source code file. CallerLineNumber: Sets the information about caller's line number. CallerMemberName: Sets the information about caller member name.

Caller information namespace CallerInformation { public class CallerInfoDemo public static void Main() ShowCallerInfo(); Console.ReadKey(); } public static void ShowCallerInfo([CallerMemberName] string callerName = null, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLine = -1) Console.WriteLine("Caller Name: {0}", callerName); Console.WriteLine("Caller FilePath: {0}", callerFilePath); Console.WriteLine("Caller Line number: {0}", callerLine);

What is new in C# 6.0 Read-only Auto-properties 9/8/2018 11:06 PM What is new in C# 6.0 Read-only Auto-properties Auto-Property Initializers index initializers nameof Expressions using static Exception filters await in catch and finally blocks Null - conditional operators Expression-bodied function members String Interpolation © 2016 Microsoft Corporation. All rights reserved. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Read-only Auto-properties Read-only auto-properties provide a more concise syntax to create immutable types.  Earlier versions of C# C# 6.0 public string FirstName { get; private set; } public string LastName { get; private set; } public string FirstName { get; } public string LastName { get; }

Auto property initializer Auto property initializer is a new concept to set the value of a property during of property declaration In C# 5.0 class Employee { public Employee() Name = "Ram"; Age = 25; Salary = 10000; } public string Name { get; set; } public int Age { get; set; } public int Salary { get; private set; } In C# 6.0 class Employee { public string Name { get; set; } = "Ram"; public int Age { get; set; } = 25; public int Salary { get; private set; } = 10000; }

Index Initializers We can directly initialize a value of a key in a Dictionary Collection by “=“ Operator In C# 5.0 In C# 6.0 Dictionary<int, string> dicInt = new Dictionary<int, string>() { {1,"Chennai"}, {2,"Madurai"}, {3,"Coimbatore"}, }; dicInt[4] = "Salem"; foreach (var item in dicInt) Console.WriteLine(item.Key + " " + item.Value); } Dictionary<int, string> dicInt = new Dictionary<int, string>() { [1] = "Chennai", [2] = "Madurai", [3] = "Coimbatore" }; dicInt[4] = "Salem"; foreach (var item in dicInt) Console.WriteLine(item.Key + " " + item.Value); }

Name of Expression class Employee { public string Name { get; set; } = "Ram"; public int Age { get; set; } = 25; public int Salary { get; private set; } = 10000; } class Program static void Main(string[] args) Employee emp = new Employee(); WriteLine("{0} : {1}", nameof(Employee.Name), emp.Name); WriteLine("{0} : {1}", nameof(Employee.Age), emp.Age); WriteLine("{0} : {1}", nameof(Employee.Salary), emp.Salary); ReadLine();

using static In C# 5.0 In C# 6.0

Exception filters Exception filters allow us to specify a condition with a catch block so if the condition will return true then the catch block is executed only if the condition is satisfied. class Program { static void Main(string[] args) int val1 = 0; int val2 = 0; try WriteLine("Enter first value :"); val1 = int.Parse(ReadLine()); WriteLine("Enter Next value :"); val2 = int.Parse(ReadLine()); WriteLine("Div : {0}", (val1 / val2)); } catch (Exception ex) when (val2 == 0) { WriteLine("Can't be Division by zero ☺"); } catch (Exception ex) WriteLine(ex.Message); Console.ReadLine();

Await in catch and finally block public class MyMath { public async void Div(int value1, int value2) try int res = value1 / value2; WriteLine("Div : {0}", res); } catch (Exception ex) await asyncMethodForCatch(); finally await asyncMethodForFinally(); private async Task asyncMethodForFinally() { WriteLine("Method from async finally Method !!"); } private async Task asyncMethodForCatch() WriteLine("Method from async Catch Method !!");

Null-Conditional Operator Reducing lines of code Null conditional operator (?.) if (response != null && response.Results != null && response.Results.Status == Status.Success) { Console.WriteLine("We were successful!"); } if (response?.Results?.Status == Status.Success) { Console.WriteLine("We were successful!"); }

Expression–Bodied Methods class Program { static void Main(string[] args) WriteLine(GetTime()); ReadLine(); } public static string GetTime() return "Current Time - " + DateTime.Now.ToString("hh:mm:ss"); class Program { static void Main(string[] args) WriteLine(GetTime()); ReadLine(); } public static string GetTime() => "Current Time - " + DateTime.Now.ToString("hh:mm:ss");

String Interpolation static void Main(string[] args) { string FirstName = "Kuppurasu"; string LastName = "Nagaraj"; string output = String.Format("{0} - {1}", FirstName, LastName); WriteLine(output); ReadLine(); } static void Main(string[] args) { string FirstName = "Kuppurasu"; string LastName = "Nagaraj"; string output = $"{FirstName} - {LastName}"; WriteLine(output); ReadLine(); }

What is new in C# 7.0 out variables Tuples Pattern Matching 9/8/2018 11:06 PM What is new in C# 7.0 out variables Tuples Pattern Matching ref locals and returns Local Functions More expression-bodied members throw Expressions Generalized async return types Numeric literal syntax improvements Non-nullable reference types © 2016 Microsoft Corporation. All rights reserved. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Microsoft Connect 2016 9/8/2018 11:06 PM Local Functions This is the ability to declare methods and types in your block scope. static void Main() { string GetAgeGroup(int age) if (age < 10) return "Child"; else if (age < 50) return "Adult"; else return "Old"; } Console.WriteLine("My age group is {0}", GetAgeGroup(33)); Console.ReadKey(); Many designs for classes include methods that are called from only one location. These additional private methods keep each method small and focused.  It easier for readers of the class to see that the local method is only called from the context in which is it declared. © 2016 Microsoft Corporation. All rights reserved. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Binary Literals public const int One = 0b0001; public const int Two = 0b0010; public const int Four = 0b0100; public const int Eight = 0b1000;

Numeric literal syntax improvements Microsoft Connect 2016 9/8/2018 11:06 PM Numeric literal syntax improvements int bin = 0b1001_1010_0001_0100; int hex = 0x1b_a0_44_fe; int dec = 33_554_432; int weird = 100_000; double real = 1_000.111_1e-1_000; © 2016 Microsoft Corporation. All rights reserved. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Pattern Matching In C# 7.0 , patterns are applied to the two existing language feature that includes is expression switch statement

is expression static void Main(string[] args) { dynamic input = null; Demo1(input); input = "Kuppu"; Console.ReadLine(); } public static void Demo1(object input) if (input is null) Console.WriteLine("Null Value"); // Check if the input is of type string , if yes , extract the value to tempStr if (input is string tempStr) Console.WriteLine(tempStr);

switch statement int powerUnits = 150; //object powerUnits = "150"; switch (powerUnits) { case int i when i > 100: WriteLine("Sufficient power units."); break; case int i: WriteLine("Insufficient power units."); default: WriteLine("Unknown power units."); }

Non-nullable reference types int a; //non-nullable value type int? b; //nullable value type string! c; //non-nullable reference type string d; //nullable reference type MyClass a; // Nullable reference type MyClass! b; // Non-nullable reference type a = null; // OK, this is nullable b = null; // Error, b is non-nullable b = a; // Error, a might be null, b can't be null

More expression-bodied members In C# 7, you can implement constructors, finalizers, and get and set accessors on properties and indexers. public class ExpressionMembersExample { // Expression-bodied constructor public ExpressionMembersExample(string label) => this.Label = label; // Expression-bodied finalizer ~ExpressionMembersExample() => Console.Error.WriteLine("Finalized!"); private string label; // Expression-bodied get / set accessors. public string Label get => label; set => this.label = value ?? "Default label"; }

out variables static void Main(string[] args) { string firstName; Microsoft Connect 2016 9/8/2018 11:06 PM out variables static void Main(string[] args) { string firstName; string lastName; CreateName(out firstName, out lastName); Console.WriteLine($"Hello {firstName} {lastName}"); } The most common reason for grouping up of temporary variables is to return multiple values from a method.  static void Main(string[] args) { CreateName(out string firstName, out string lastName); Console.WriteLine($"Hello {firstName} {lastName}"); } © 2016 Microsoft Corporation. All rights reserved. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Throw Exception from Expression In C# 7, we can throw an exception directly through expression. Thus, an exception can be thrown from an expression. class Program { static void Main(string[] args) var a = Divide(10, 0); } public static double Divide(int x, int y) return y != 0 ? x % y : throw new DivideByZeroException();

Ref locals and returns private static ref int GetBiggerNumber(ref int num1, ref int num2) { ref int localVariable = ref num1; if (num1 > num2) return ref num1; else return ref num2; }

Microsoft Connect 2016 9/8/2018 11:06 PM Tubles A tuple allows us to combine multiple values of possibly different types into a single object without having to create a custom class.  //types of struct members are automatically inferred by the compiler as string,string var genders = ("Male", "Female"); Console.WriteLine("Possible genders in human race are : {0} and {1} ", genders.Item1, genders.Item2); Console.WriteLine($"Possible genders in human race are {genders.Item1}, {genders.Item2}."); //hetrogeneous data types are also possible in tuple. var employeeDetail = ("Michael", 33, true); //(string,int,bool) Console.WriteLine("Details of employee are Name: {0}, Age : {1}, IsPermanent: {2} ", employeeDetail.Item1, employeeDetail.Item2, employeeDetail.Item3); C# provides a rich syntax used for classes and structs provides to explain your design intent. But sometimes that rich syntax requires extra work with minimal benefit. © 2016 Microsoft Corporation. All rights reserved. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.