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

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
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
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

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