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

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Recently uploaded (20)

The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 

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