SlideShare a Scribd company logo
1 of 18
My Swiss Army Knife
What’s new in C# 6.0
Fiyaz Hasan (Fizz)
Intern, Microsoft Bangladesh.
Living in Dhaka. Founder of Geek Hour, Technical Blog Writer, Gamer, Guitarist and of
course a Software Engineer.
www.fiyazhasan.me
www.facebook.com/alsoknownasfizz
StaticNamespaceasusing using System;
namespace NewInCSharp
{
class Program
{
static void Main(string[] args)
{
MySelf.WhoAmI();
Console.ReadKey();
}
}
static class MySelf
{
public static void WhoAmI()
{
Console.WriteLine("I'm Fizz!");
}
}
}
using static System.Console;
using static NewInCSharp.MySelf;
namespace NewInCSharp
{
class Program
{
static void Main(string[] args)
{
WhoAmI();
ReadKey();
}
}
static class MySelf
{
public static void WhoAmI()
{
WriteLine("I'm Fizz!");
}
}
}
static namespace using
StringInterpolation using System;
using System.Collections.Generic;
using static System.Console;
namespace NewInCSharp
{
class Program
{
private static void Main(string[]
args)
{
string name = "Murphy Cooper";
string planet = "Cooper Station";
WriteLine("{0} is actually named
after {1}", planet, name);
ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using static System.Console;
namespace NewInCSharp
{
class Program
{
private static void Main(string[]
args)
{
string name = "Murphy Cooper";
string planet = "Cooper Station";
WriteLine($"{planet} is actually
named after {name}");
ReadLine();
}
}
} String interpolation
DictionaryInitializers using System.Collections.Generic;
using static System.Console;
namespace NewInCSharp
{
class Program
{
private static void Main(string[] args)
{
Dictionary<string, string> alien = new Dictionary<string, string>()
{
{"Name", "Fizzy"},
{"Planet", "Kepler-452b"}
};
foreach (KeyValuePair<string, string> keyValuePair in alien)
{
WriteLine(keyValuePair.Key + ": " + keyValuePair.Value + "n");
}
ReadLine();
}
}
}
DictionaryInitializers(continues) using System.Collections.Generic;
using static System.Console;
namespace NewInCSharp
{
class Program
{
private static void Main(string[] args)
{
Dictionary<string, string> alien = new Dictionary<string, string>()
{
["Name"] = "Fizzy",
["Planet"] = "Kepler-452b"
};
foreach (KeyValuePair<string, string> keyValuePair in alien)
{
WriteLine(keyValuePair.Key + ": " + keyValuePair.Value + "n");
}
ReadLine();
}
}
}
New way of initializing dictionary
Auto-PropertyInitializers using static System.Console;
namespace NewInCSharp
{
class Program
{
static void Main(string[] args)
{
Employee employee = new Employee();
employee.Name = "Bill Gates";
WriteLine("Name: " + employee.Name + "nSalary: " + employee.Salary);
ReadKey();
}
public class Employee
{
public string Name { get; set; }
public decimal Salary { get; set; }
public Employee()
{
Salary = 10000;
}
}
}
}
Auto-PropertyInitializers(continues) using static System.Console;
namespace NewInCSharp
{
class Program
{
static void Main(string[] args)
{
Employee employee = new Employee();
employee.Name = " Bill Gates";
WriteLine("Name: " + employee.Name + "nSalary: " + employee.Salary);
ReadKey();
}
public class Employee
{
public string Name { get; set; }
public decimal Salary { get; set; } = 10000;
}
}
} Constructor gone & Initialized
Property
nameofexpression class Program
{
private static void Main(string[] args)
{
try
{
CallSomething();
}
catch (Exception exception)
{
WriteLine(exception.Message);
}
ReadKey();
}
private static void CallSomething()
{
int? number = null;
if (number == null)
{
throw new Exception(nameof(number) +
" is null");
}
}
} Good for Refactoring
class Program
{
private static void Main(string[] args)
{
try
{
CallSomething();
}
catch (Exception exception)
{
WriteLine(exception.Message);
}
ReadKey();
}
private static void CallSomething()
{
int? x = null;
if (x == null)
{
throw new Exception("x is null");
}
}
}
awaitincatch/finally private static void Main(string[] args)
{
Task.Factory.StartNew(() => GetWeather());
Console.ReadKey();
}
private async static Task GetWeather()
{
HttpClient client = new HttpClient();
try
{
var result = await client.GetStringAsync("http://api.openweathermap.org/data/2.5/weather?q=Dhaka,
Console.WriteLine(result);
}
catch (Exception exception)
{
try
{
var result = await client.GetStringAsync("http://api.openweathermap.org/data/2.5/weather?q=Ne
Console.WriteLine(result);
}
catch (Exception)
{
throw;
}
}
}
Wasn’t possible in C# 5.0 but now
ALL IS WELL in C# 6.0
class Program
{
private static void Main(string[] args)
{
SuperHero hero = new SuperHero();
if (hero.SuperPower == String.Empty)
{
hero = null;
}
Console.WriteLine(hero != null ?
hero.SuperPower : "You aint a super hero.");
Console.ReadLine();
}
}
public class SuperHero
{
public string SuperPower { get; set; } = "";
}
Nullconditionaloperator class Program
{
private static void Main(string[] args)
{
SuperHero hero = new SuperHero();
if (hero.SuperPower == String.Empty)
{
hero = null;
}
Console.WriteLine(hero?.SuperPower ??
"You aint a super hero.");
Console.ReadLine();
}
}
public class SuperHero
{
public string SuperPower { get; set; } = "";
}
class Program
{
private static void Main(string[] args)
{
List<SuperHero> superHeroes = null;
SuperHero hero = new SuperHero();
if (hero.SuperPower != String.Empty)
{
superHeroes = new List<SuperHero>();
superHeroes.Add(hero);
}
Console.WriteLine(superHeroes != null ? superHeroes[0].SuperPower : "There is no such thing as
super heroes.");
Console.ReadLine();
}
}
public class SuperHero
{
public string SuperPower { get; set; } = "";
}
Nullconditionaloperator(continues)
class Program
{
private static void Main(string[] args)
{
List<SuperHero> superHeroes = null;
SuperHero hero = new SuperHero();
if (hero.SuperPower != String.Empty)
{
superHeroes = new List<SuperHero>();
superHeroes.Add(hero);
}
Console.WriteLine(superHeroes?[0].SuperPower ?? "There is no such thing as super heros.");
Console.ReadLine();
}
}
public class SuperHero
{
public string SuperPower { get; set; } = "";
}
Nullconditionaloperator(continues)
public class Movie : INotifyPropertyChanged
{
public string Title { get; set; }
public int Rating { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
Nullpropagation
handler?.Invoke(this, new PropertyChangedEventArgs(name));
Null Propagation
internal class Program
{
private static void Main(string[] args)
{
double x = 1.618;
double y = 3.142;
Console.WriteLine(AddNumbers(x, y));
Console.ReadLine();
}
private static double AddNumbers(double x, double y)
{
return x + y;
}
}
Expressionbodies(onmethod)
private static double AddNumbers(double x, double y) => x + y;
New expression bodied function syntax
internal class Program
{
private static void Main(string[] args)
{
Person person = new Person();
WriteLine("I'm " + person.FullName);
ReadLine();
}
public class Person
{
public string FirstName { get; } = "Fiyaz";
public string LastName { get; } = "Hasan";
public string FullName => FirstName + " " + LastName;
}
}
Expressionbodies(onproperty)
Expression bodies on property-like function members
internal class Program
{
private static void Main(string[] args)
{
Shape shape = new Shape();
ShapeUtility.GenerateRandomSides(shape);
WriteLine(shape.IsPolygon());
ReadLine();
}
}
public class Shape
{
public int Sides { get; set; }
}
public static class ShapeUtility
{
public static bool IsPolygon(this Shape shape)
{
return shape.Sides >= 3;
}
public static void GenerateRandomSides(Shape shape)
{
Random random = new Random();
shape.Sides = random.Next(1, 6);
}
}
StaticusingwithExtensionmethod
Extension Method
Static Method
internal class Program
{
private static void Main(string[] args)
{
Shape shape = new Shape();
GenerateRandomSides(shape);
WriteLine(shape.IsPolygon());
ReadLine();
}
}
public class Shape
{
public int Sides { get; set; }
}
public static class ShapeUtility
{
public static bool IsPolygon(this Shape shape)
{
return shape.Sides >= 3;
}
public static void GenerateRandomSides(Shape shape)
{
Random random = new Random();
shape.Sides = random.Next(1, 6);
}
StaticusingswithExtensionmethod
(continues)
using static NewInCSharp.ShapeUtility;
Since extension methods are static
methods, if static using are used then
extension methods cant be found in
global scope. So they are imported as
extension methods. And you can’t just
invoke them like normal static functions

More Related Content

What's hot

Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Susan Potter
 
Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code genkoji lin
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistAnton Arhipov
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programingwahyuseptiansyah
 
The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212Mahmoud Samir Fayed
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」matuura_core
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Kenji Tanaka
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harianKhairunnisaPekanbaru
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системеDEVTYPE
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 

What's hot (20)

Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
V8
V8V8
V8
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
 
Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code gen
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
 
The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212
 
Tugas 2
Tugas 2Tugas 2
Tugas 2
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 

Similar to What’s new in C# 6

Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBOren Eini
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistAnton Arhipov
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2Technopark
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Anton Arhipov
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Answer this question for quality assurance. Include a final applicat.pdf
Answer this question for quality assurance. Include a final applicat.pdfAnswer this question for quality assurance. Include a final applicat.pdf
Answer this question for quality assurance. Include a final applicat.pdfakanshanawal
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationJoni
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesAndrey Karpov
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agentsRafael Winterhalter
 

Similar to What’s new in C# 6 (20)

C# Is The Future
C# Is The FutureC# Is The Future
C# Is The Future
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDB
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Java programs
Java programsJava programs
Java programs
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012
 
CSharp v1.0.2
CSharp v1.0.2CSharp v1.0.2
CSharp v1.0.2
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Answer this question for quality assurance. Include a final applicat.pdf
Answer this question for quality assurance. Include a final applicat.pdfAnswer this question for quality assurance. Include a final applicat.pdf
Answer this question for quality assurance. Include a final applicat.pdf
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Lab4
Lab4Lab4
Lab4
 
Easy Button
Easy ButtonEasy Button
Easy Button
 

More from Fiyaz Hasan

Hands free with cortana
Hands free with cortanaHands free with cortana
Hands free with cortanaFiyaz Hasan
 
Up & Running with Polymer
Up & Running with PolymerUp & Running with Polymer
Up & Running with PolymerFiyaz Hasan
 
Preventing XSRF in ASP.NET CORE apps
Preventing XSRF in ASP.NET CORE appsPreventing XSRF in ASP.NET CORE apps
Preventing XSRF in ASP.NET CORE appsFiyaz Hasan
 
Azure push notification hub
Azure push notification hubAzure push notification hub
Azure push notification hubFiyaz Hasan
 
Tales of Two Brothers
Tales of Two BrothersTales of Two Brothers
Tales of Two BrothersFiyaz Hasan
 
When You Cant Code You Can Blend
When You Cant Code You Can BlendWhen You Cant Code You Can Blend
When You Cant Code You Can BlendFiyaz Hasan
 
Walk in the shoe of angular
Walk in the shoe of angularWalk in the shoe of angular
Walk in the shoe of angularFiyaz Hasan
 
Building Windows Phone Database App Using MVVM Pattern
Building Windows Phone Database App Using MVVM PatternBuilding Windows Phone Database App Using MVVM Pattern
Building Windows Phone Database App Using MVVM PatternFiyaz Hasan
 
Play With Windows Phone Local Database
Play With Windows Phone Local DatabasePlay With Windows Phone Local Database
Play With Windows Phone Local DatabaseFiyaz Hasan
 

More from Fiyaz Hasan (9)

Hands free with cortana
Hands free with cortanaHands free with cortana
Hands free with cortana
 
Up & Running with Polymer
Up & Running with PolymerUp & Running with Polymer
Up & Running with Polymer
 
Preventing XSRF in ASP.NET CORE apps
Preventing XSRF in ASP.NET CORE appsPreventing XSRF in ASP.NET CORE apps
Preventing XSRF in ASP.NET CORE apps
 
Azure push notification hub
Azure push notification hubAzure push notification hub
Azure push notification hub
 
Tales of Two Brothers
Tales of Two BrothersTales of Two Brothers
Tales of Two Brothers
 
When You Cant Code You Can Blend
When You Cant Code You Can BlendWhen You Cant Code You Can Blend
When You Cant Code You Can Blend
 
Walk in the shoe of angular
Walk in the shoe of angularWalk in the shoe of angular
Walk in the shoe of angular
 
Building Windows Phone Database App Using MVVM Pattern
Building Windows Phone Database App Using MVVM PatternBuilding Windows Phone Database App Using MVVM Pattern
Building Windows Phone Database App Using MVVM Pattern
 
Play With Windows Phone Local Database
Play With Windows Phone Local DatabasePlay With Windows Phone Local Database
Play With Windows Phone Local Database
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
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
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 

Recently uploaded (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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 New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

What’s new in C# 6

  • 1. My Swiss Army Knife What’s new in C# 6.0
  • 2. Fiyaz Hasan (Fizz) Intern, Microsoft Bangladesh. Living in Dhaka. Founder of Geek Hour, Technical Blog Writer, Gamer, Guitarist and of course a Software Engineer. www.fiyazhasan.me www.facebook.com/alsoknownasfizz
  • 3. StaticNamespaceasusing using System; namespace NewInCSharp { class Program { static void Main(string[] args) { MySelf.WhoAmI(); Console.ReadKey(); } } static class MySelf { public static void WhoAmI() { Console.WriteLine("I'm Fizz!"); } } } using static System.Console; using static NewInCSharp.MySelf; namespace NewInCSharp { class Program { static void Main(string[] args) { WhoAmI(); ReadKey(); } } static class MySelf { public static void WhoAmI() { WriteLine("I'm Fizz!"); } } } static namespace using
  • 4. StringInterpolation using System; using System.Collections.Generic; using static System.Console; namespace NewInCSharp { class Program { private static void Main(string[] args) { string name = "Murphy Cooper"; string planet = "Cooper Station"; WriteLine("{0} is actually named after {1}", planet, name); ReadLine(); } } } using System; using System.Collections.Generic; using static System.Console; namespace NewInCSharp { class Program { private static void Main(string[] args) { string name = "Murphy Cooper"; string planet = "Cooper Station"; WriteLine($"{planet} is actually named after {name}"); ReadLine(); } } } String interpolation
  • 5. DictionaryInitializers using System.Collections.Generic; using static System.Console; namespace NewInCSharp { class Program { private static void Main(string[] args) { Dictionary<string, string> alien = new Dictionary<string, string>() { {"Name", "Fizzy"}, {"Planet", "Kepler-452b"} }; foreach (KeyValuePair<string, string> keyValuePair in alien) { WriteLine(keyValuePair.Key + ": " + keyValuePair.Value + "n"); } ReadLine(); } } }
  • 6. DictionaryInitializers(continues) using System.Collections.Generic; using static System.Console; namespace NewInCSharp { class Program { private static void Main(string[] args) { Dictionary<string, string> alien = new Dictionary<string, string>() { ["Name"] = "Fizzy", ["Planet"] = "Kepler-452b" }; foreach (KeyValuePair<string, string> keyValuePair in alien) { WriteLine(keyValuePair.Key + ": " + keyValuePair.Value + "n"); } ReadLine(); } } } New way of initializing dictionary
  • 7. Auto-PropertyInitializers using static System.Console; namespace NewInCSharp { class Program { static void Main(string[] args) { Employee employee = new Employee(); employee.Name = "Bill Gates"; WriteLine("Name: " + employee.Name + "nSalary: " + employee.Salary); ReadKey(); } public class Employee { public string Name { get; set; } public decimal Salary { get; set; } public Employee() { Salary = 10000; } } } }
  • 8. Auto-PropertyInitializers(continues) using static System.Console; namespace NewInCSharp { class Program { static void Main(string[] args) { Employee employee = new Employee(); employee.Name = " Bill Gates"; WriteLine("Name: " + employee.Name + "nSalary: " + employee.Salary); ReadKey(); } public class Employee { public string Name { get; set; } public decimal Salary { get; set; } = 10000; } } } Constructor gone & Initialized Property
  • 9. nameofexpression class Program { private static void Main(string[] args) { try { CallSomething(); } catch (Exception exception) { WriteLine(exception.Message); } ReadKey(); } private static void CallSomething() { int? number = null; if (number == null) { throw new Exception(nameof(number) + " is null"); } } } Good for Refactoring class Program { private static void Main(string[] args) { try { CallSomething(); } catch (Exception exception) { WriteLine(exception.Message); } ReadKey(); } private static void CallSomething() { int? x = null; if (x == null) { throw new Exception("x is null"); } } }
  • 10. awaitincatch/finally private static void Main(string[] args) { Task.Factory.StartNew(() => GetWeather()); Console.ReadKey(); } private async static Task GetWeather() { HttpClient client = new HttpClient(); try { var result = await client.GetStringAsync("http://api.openweathermap.org/data/2.5/weather?q=Dhaka, Console.WriteLine(result); } catch (Exception exception) { try { var result = await client.GetStringAsync("http://api.openweathermap.org/data/2.5/weather?q=Ne Console.WriteLine(result); } catch (Exception) { throw; } } } Wasn’t possible in C# 5.0 but now ALL IS WELL in C# 6.0
  • 11. class Program { private static void Main(string[] args) { SuperHero hero = new SuperHero(); if (hero.SuperPower == String.Empty) { hero = null; } Console.WriteLine(hero != null ? hero.SuperPower : "You aint a super hero."); Console.ReadLine(); } } public class SuperHero { public string SuperPower { get; set; } = ""; } Nullconditionaloperator class Program { private static void Main(string[] args) { SuperHero hero = new SuperHero(); if (hero.SuperPower == String.Empty) { hero = null; } Console.WriteLine(hero?.SuperPower ?? "You aint a super hero."); Console.ReadLine(); } } public class SuperHero { public string SuperPower { get; set; } = ""; }
  • 12. class Program { private static void Main(string[] args) { List<SuperHero> superHeroes = null; SuperHero hero = new SuperHero(); if (hero.SuperPower != String.Empty) { superHeroes = new List<SuperHero>(); superHeroes.Add(hero); } Console.WriteLine(superHeroes != null ? superHeroes[0].SuperPower : "There is no such thing as super heroes."); Console.ReadLine(); } } public class SuperHero { public string SuperPower { get; set; } = ""; } Nullconditionaloperator(continues)
  • 13. class Program { private static void Main(string[] args) { List<SuperHero> superHeroes = null; SuperHero hero = new SuperHero(); if (hero.SuperPower != String.Empty) { superHeroes = new List<SuperHero>(); superHeroes.Add(hero); } Console.WriteLine(superHeroes?[0].SuperPower ?? "There is no such thing as super heros."); Console.ReadLine(); } } public class SuperHero { public string SuperPower { get; set; } = ""; } Nullconditionaloperator(continues)
  • 14. public class Movie : INotifyPropertyChanged { public string Title { get; set; } public int Rating { get; set; } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } Nullpropagation handler?.Invoke(this, new PropertyChangedEventArgs(name)); Null Propagation
  • 15. internal class Program { private static void Main(string[] args) { double x = 1.618; double y = 3.142; Console.WriteLine(AddNumbers(x, y)); Console.ReadLine(); } private static double AddNumbers(double x, double y) { return x + y; } } Expressionbodies(onmethod) private static double AddNumbers(double x, double y) => x + y; New expression bodied function syntax
  • 16. internal class Program { private static void Main(string[] args) { Person person = new Person(); WriteLine("I'm " + person.FullName); ReadLine(); } public class Person { public string FirstName { get; } = "Fiyaz"; public string LastName { get; } = "Hasan"; public string FullName => FirstName + " " + LastName; } } Expressionbodies(onproperty) Expression bodies on property-like function members
  • 17. internal class Program { private static void Main(string[] args) { Shape shape = new Shape(); ShapeUtility.GenerateRandomSides(shape); WriteLine(shape.IsPolygon()); ReadLine(); } } public class Shape { public int Sides { get; set; } } public static class ShapeUtility { public static bool IsPolygon(this Shape shape) { return shape.Sides >= 3; } public static void GenerateRandomSides(Shape shape) { Random random = new Random(); shape.Sides = random.Next(1, 6); } } StaticusingwithExtensionmethod Extension Method Static Method
  • 18. internal class Program { private static void Main(string[] args) { Shape shape = new Shape(); GenerateRandomSides(shape); WriteLine(shape.IsPolygon()); ReadLine(); } } public class Shape { public int Sides { get; set; } } public static class ShapeUtility { public static bool IsPolygon(this Shape shape) { return shape.Sides >= 3; } public static void GenerateRandomSides(Shape shape) { Random random = new Random(); shape.Sides = random.Next(1, 6); } StaticusingswithExtensionmethod (continues) using static NewInCSharp.ShapeUtility; Since extension methods are static methods, if static using are used then extension methods cant be found in global scope. So they are imported as extension methods. And you can’t just invoke them like normal static functions