SlideShare una empresa de Scribd logo
1 de 27
Алексей Соммер
New C# features
C# 1.0 Visual Studio 2002
Retrospective
C# 2.0 Visual Studio 2005 - Generics, Anonymous methods, iterators/yield, static classes
C# 3.0 Visual Studio 2008 - LINQ, Lambda Expressions, Implicit typing, Extension methods
C# 6.0 Visual Studio 2015 - Null-conditional operators, String Interpolation
C# 5.0 Visual Studio 2012 - async/await, Caller Information, some breaking changes
C# 4.0 Visual Studio 2010 - dynamic, Optional parameters and named arguments
C# 7.0 Visual Studio 2017 - Tuples, Pattern matching, Local functions
C# 1.1 Visual Studio 2003 - #line, pragma, xml doc comments
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string prop = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
OnPropertyChanged(); OnPropertyChanged("Price");
From F# to C#
Tuples
LINQ
Immutability
Pattern matching
Exception filters
Auto-property initializers
Expression-bodied function members
try
{
SomeMethod(param);
}
catch (Exception e) when (param != null)
{
}
Exception filters
public string AppUrl { get; set; } = "http://lalala.com";
public string AppUrl { get; set; } = InitializeProperty();
public static string InitializeProperty()
{
return "http://lalala.com ";
}
Auto-property initializers
public int Sum(int x, int y)
{
return x+y;
}
public string ServerIP { get { return "65.23.135.201"; } }
public int Sum(int x, int y) => x+y;
public string ServerIP => "65.23.135.201";
Expression-bodied function members
C# 7 Work List of Features
bit.ly/1E1nrJZ
Language Feature Status
bit.ly/1TKZAHc
Tuples
There no need anymore to create new class if you want to
send or get multiple parameters!
var unnamed = (35, "What is your age?");
unnamed.Item1 == named.Answer
var named = (Answer: 35, Question: "What’s your age again?");
(int, string) GetXY()
{
int x = 1;
string y = "One";
return (x, y);
}
Simplest example
var xy = GetXY();
Deconstruction
(int, List<string>) GetListWithId()
{
int x = 1;
List<string> y = new List<string>();
return (x, y);
}
(int x, List<string> y) = GetListWithId();
var (x, y) = GetXY();
public class Coordinates
{
public int X { get; }
public int Y { get; }
public Coordinates(int x, int y)
{
X = x;
Y = y;
}
public void Deconstruct(out int x, out int y)
{
x = X;
y = Y;
}
}
Coordinates xy =
new Coordinates(5, 7);
(int x, int y) = xy;
User defined types
Pattern Matching
if (someObject is Customer)
{
var c = (Customer)someObject;
c.Balance = c.Balance + 1000;
}
if (someObject is Customer c) c.Balance = c.Balance + 1000;
switch (userRole)
{
case Manager m:
return m.Salary;
case Partner p:
return p.Income;
}
Case
switch (userRole)
{
case Manager m with Salary<1500:
return m.Salary*1.2;
case Manager m:
return m.Salary;
case Partner p:
return p.Income;
}
Case …. with
C# 7.1 features
Async Main
default literal
Infer tuple names
Pattern-matching with generics
Reference assemblies
static void Main(string[] args)
{
DoWork().GetAwaiter().GetResult();
}
static void Main(string[] args)
{
DoWork().Wait();
}
static async Task DoWork() { }
any exception
AggregateException
Boilerplate code
async Main
default
int i = default;
Instead of
int i = default(int);
Infer Tuple Names
explicit names
var tuple = (a: x.a, y: x.y);
inferred names
var tuple = (x.a, y);
Infer tuple names
int x=1;
Action y = () => SomeMethod();
var tuple = (a: x, y);
tuple.y();
Aaa! It’s breaking back compatibility!
// previously
public static class ExtClass
{
public static void y(this (int, Action) z)
{
}
}
// now
void SomeMethod() { }
Pattern-matching with generics
class Manager : Person { }
class Employee : Person { }
……………
Employee m = new Employee();
IncreaseSalary<Employee>(m);
……………
public void IncreaseSalary<T>(T person) where T : Person
{
if (person is Manager m) person.Salary++;
}
Readonly ref
static Employee CreateCopy(ref Position p)
{
// don’t change p value!
return new Position() { Lat = p.Lat, Long = p.Long };
}
static Employee CreateCopy(ref readonly Position p)
{
p.Lat = 54.32654;
SomeMethod(ref p.Lat);
return new Position() { Lat = p.Lat , Long = p.Long };
}
Non-trailing named arguments
int SomeMethod(int x, int y)
{
return (x - y) * (x + y);
}
SomeMethod(11, 27)
SomeMethod(y:17, x:21)
SomeMethod(11, y:27)
SomeMethod(x:12, 11)
Why?
int SomeMethod(int y, int x) { return 1; }
int SomeMethod<T>(int x, T y) { return 2; }
SomeMethod(x: 17, y: 21); // calls first SomeMethod
SomeMethod(11, y: 27); // calls second SomeMethod
Drawbacks
blittable
blittable struct BlittableOrNot
{
public byte a;
public bool b;
public int c;
}
blittable struct BlittableOrNot
{
public byte a;
public double b;
public int c;
}
Default Interface Methods
1. Currently if you want to change interface then you should change
all implementations
2. What if class will try to implement two interfaces having a default
method with the same signature?
3. Interfaces are still different from abstract classes
> Спасибо за внимание!
> Алексей Соммер
> asommer@yandex.ru
> skype: alexejsommer

Más contenido relacionado

La actualidad más candente

Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»SpbDotNet Community
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project FileDeyvessh kumar
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScripttmont
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)hhliu
 
Understanding storage class using nm
Understanding storage class using nmUnderstanding storage class using nm
Understanding storage class using nmmohamed sikander
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Anton Bikineev
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Sumant Tambe
 
Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]Palak Sanghani
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerSrikanth Shreenivas
 
Lambda Expressions in C++
Lambda Expressions in C++Lambda Expressions in C++
Lambda Expressions in C++Patrick Viafore
 

La actualidad más candente (20)

Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 
Qno 1 (d)
Qno 1 (d)Qno 1 (d)
Qno 1 (d)
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
C program
C programC program
C program
 
Templates
TemplatesTemplates
Templates
 
Cquestions
Cquestions Cquestions
Cquestions
 
Array notes
Array notesArray notes
Array notes
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Understanding storage class using nm
Understanding storage class using nmUnderstanding storage class using nm
Understanding storage class using nm
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]
 
Function basics
Function basicsFunction basics
Function basics
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 
Lambda Expressions in C++
Lambda Expressions in C++Lambda Expressions in C++
Lambda Expressions in C++
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 

Similar a New C# features

C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Codemotion
 
Les nouveautés de C# 6
Les nouveautés de C# 6Les nouveautés de C# 6
Les nouveautés de C# 6Microsoft
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...tdc-globalcode
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Sheik Uduman Ali
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Pragmatic metaprogramming
Pragmatic metaprogrammingPragmatic metaprogramming
Pragmatic metaprogrammingMårten Rånge
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and AnalysisWiwat Ruengmee
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingabhay singh
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
 
[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8Alonso Torres
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mark Needham
 

Similar a New C# features (20)

Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 
Les nouveautés de C# 6
Les nouveautés de C# 6Les nouveautés de C# 6
Les nouveautés de C# 6
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
C# 7.0, 7.1, 7.2
C# 7.0, 7.1, 7.2C# 7.0, 7.1, 7.2
C# 7.0, 7.1, 7.2
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Pragmatic metaprogramming
Pragmatic metaprogrammingPragmatic metaprogramming
Pragmatic metaprogramming
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
 
02.adt
02.adt02.adt
02.adt
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
L10
L10L10
L10
 
[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 

Último (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

New C# features

  • 2. C# 1.0 Visual Studio 2002 Retrospective C# 2.0 Visual Studio 2005 - Generics, Anonymous methods, iterators/yield, static classes C# 3.0 Visual Studio 2008 - LINQ, Lambda Expressions, Implicit typing, Extension methods C# 6.0 Visual Studio 2015 - Null-conditional operators, String Interpolation C# 5.0 Visual Studio 2012 - async/await, Caller Information, some breaking changes C# 4.0 Visual Studio 2010 - dynamic, Optional parameters and named arguments C# 7.0 Visual Studio 2017 - Tuples, Pattern matching, Local functions C# 1.1 Visual Studio 2003 - #line, pragma, xml doc comments
  • 3. public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string prop = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop)); } OnPropertyChanged(); OnPropertyChanged("Price");
  • 4. From F# to C# Tuples LINQ Immutability Pattern matching Exception filters Auto-property initializers Expression-bodied function members
  • 5. try { SomeMethod(param); } catch (Exception e) when (param != null) { } Exception filters
  • 6. public string AppUrl { get; set; } = "http://lalala.com"; public string AppUrl { get; set; } = InitializeProperty(); public static string InitializeProperty() { return "http://lalala.com "; } Auto-property initializers
  • 7. public int Sum(int x, int y) { return x+y; } public string ServerIP { get { return "65.23.135.201"; } } public int Sum(int x, int y) => x+y; public string ServerIP => "65.23.135.201"; Expression-bodied function members
  • 8. C# 7 Work List of Features bit.ly/1E1nrJZ Language Feature Status bit.ly/1TKZAHc
  • 9. Tuples There no need anymore to create new class if you want to send or get multiple parameters! var unnamed = (35, "What is your age?"); unnamed.Item1 == named.Answer var named = (Answer: 35, Question: "What’s your age again?");
  • 10. (int, string) GetXY() { int x = 1; string y = "One"; return (x, y); } Simplest example var xy = GetXY();
  • 11. Deconstruction (int, List<string>) GetListWithId() { int x = 1; List<string> y = new List<string>(); return (x, y); } (int x, List<string> y) = GetListWithId(); var (x, y) = GetXY();
  • 12. public class Coordinates { public int X { get; } public int Y { get; } public Coordinates(int x, int y) { X = x; Y = y; } public void Deconstruct(out int x, out int y) { x = X; y = Y; } } Coordinates xy = new Coordinates(5, 7); (int x, int y) = xy; User defined types
  • 13. Pattern Matching if (someObject is Customer) { var c = (Customer)someObject; c.Balance = c.Balance + 1000; } if (someObject is Customer c) c.Balance = c.Balance + 1000;
  • 14. switch (userRole) { case Manager m: return m.Salary; case Partner p: return p.Income; } Case
  • 15. switch (userRole) { case Manager m with Salary<1500: return m.Salary*1.2; case Manager m: return m.Salary; case Partner p: return p.Income; } Case …. with
  • 16. C# 7.1 features Async Main default literal Infer tuple names Pattern-matching with generics Reference assemblies
  • 17. static void Main(string[] args) { DoWork().GetAwaiter().GetResult(); } static void Main(string[] args) { DoWork().Wait(); } static async Task DoWork() { } any exception AggregateException Boilerplate code async Main
  • 18. default int i = default; Instead of int i = default(int);
  • 19. Infer Tuple Names explicit names var tuple = (a: x.a, y: x.y); inferred names var tuple = (x.a, y);
  • 20. Infer tuple names int x=1; Action y = () => SomeMethod(); var tuple = (a: x, y); tuple.y(); Aaa! It’s breaking back compatibility! // previously public static class ExtClass { public static void y(this (int, Action) z) { } } // now void SomeMethod() { }
  • 21. Pattern-matching with generics class Manager : Person { } class Employee : Person { } …………… Employee m = new Employee(); IncreaseSalary<Employee>(m); …………… public void IncreaseSalary<T>(T person) where T : Person { if (person is Manager m) person.Salary++; }
  • 22. Readonly ref static Employee CreateCopy(ref Position p) { // don’t change p value! return new Position() { Lat = p.Lat, Long = p.Long }; } static Employee CreateCopy(ref readonly Position p) { p.Lat = 54.32654; SomeMethod(ref p.Lat); return new Position() { Lat = p.Lat , Long = p.Long }; }
  • 23. Non-trailing named arguments int SomeMethod(int x, int y) { return (x - y) * (x + y); } SomeMethod(11, 27) SomeMethod(y:17, x:21) SomeMethod(11, y:27) SomeMethod(x:12, 11) Why?
  • 24. int SomeMethod(int y, int x) { return 1; } int SomeMethod<T>(int x, T y) { return 2; } SomeMethod(x: 17, y: 21); // calls first SomeMethod SomeMethod(11, y: 27); // calls second SomeMethod Drawbacks
  • 25. blittable blittable struct BlittableOrNot { public byte a; public bool b; public int c; } blittable struct BlittableOrNot { public byte a; public double b; public int c; }
  • 26. Default Interface Methods 1. Currently if you want to change interface then you should change all implementations 2. What if class will try to implement two interfaces having a default method with the same signature? 3. Interfaces are still different from abstract classes
  • 27. > Спасибо за внимание! > Алексей Соммер > asommer@yandex.ru > skype: alexejsommer

Notas del editor

  1. Does someone use Caller information or even someone know what is it?
  2. Можно получить имя вызывающего метод объекта
  3. “Invasion” was started in C# 6
  4. C# 6
  5. C# 6
  6. Old style on top and new style on the bottom Works for methods and read-only properties C# 6
  7. Whole information is publicly used. You can stalking Mads Torgersen. For example in his last post he is discussing “nullable reference types“
  8. NuGet package System.ValueTuple should be installed on .NET 4.6.2 and lower. But VS will inform you about That is probably why we are still not using this feature Спасибо залу за подсказки! Tuples действительно похожи на Anonymous Types. Но anonymous types все-таки не рекомендуется использовать для возврата значения из метода: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types
  9. Deconstruction of user defined types If you can’t change the class then you could use Extensions (from C# 3.0) and add static void Deconstruct method
  10. Check is object of some type and cast to that type
  11. First version since 2002 with minor version in number
  12. Let’s say its just something like a bug fix An expression of type T cannot be handled by a pattern of type Manager
  13. Pass struct variables into method calls for readonly purposes
  14. Named method argument is on his right place, but method couldn’t be called. Why? C# 7.2
  15. As you can see from this code drawbacks have exist before this new feature So, probably drawbacks are not drawbacks. More like fix
  16. In proposal state for 7.2 Feature could be useful if you are using P/Invoke (you can only return blittable types) Common representation in both managed and unmanaged memory and do not require special handling by the interop marshaler And all objects in memory are placed in consistent order Those type help to share information between managed and unmanaged code Usable in COM Interop or P/Invoke, two techniques for interoperability in .NET applications System.Byte, System.SByte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.IntPtr, System.UIntPtr, System.Single, System.Double
  17. As previously all features where from F# - now this feature has come from Java So it would be possible to change legacy code. May be it is more needed for C# development team to add new features  (like it did java developers team) In JAVA it has helped to enhance the Collections API to support lambda expressions 2. As it done in Java default method should be overridden and could be called interface method explicitly