View
70
Download
1
Category
Preview:
Citation preview
PowerPoint Presentation
Enterprise Software Development
@EricPhan | Chief Architect @ SSWWhy you should be using the shiny new C# 6.0 features now!Join the Conversation #DevSuperPowers @EricPhan
B.E. - Software Engineering, Certified Scrum MasterEric Phan @EricPhanChief Architect @ SSWMCTS TFS, MCPLoves playing with the latest technology
HistorySummary8 Cool C# 6.0 FeaturesAgenda
Weve come a long wayJoin the Conversation #DevSuperPowers @EricPhan
Join the Conversation #DevSuperPowers @EricPhan
public class Developer{ public Developer() { DrinksCoffee = true; } public bool DrinksCoffee { get; set; }}
History2002 - C# 1.0released with .NET 1.0 and VS20022003 - C# 1.2released with .NET 1.1 and VS2003 First version to callDisposeonIEnumerators which implementedIDisposable. A few other small features.2005 - C# 2.0released with .NET 2.0 and VS2005 Generics, anonymous methods, nullable types, iterator blocks
Credit to Jon Skeet - http://stackoverflow.com/a/247623
History2007 - C# 3.0released with .NET 3.5 and VS2008Lambda expressions, extension methods, expression trees, anonymous types, implicit typing (var), query expressions2010 - C# 4.0released with .NET 4 and VS2010 Late binding (dynamic), delegate and interface generic variance, more COM support, named arguments, tuple data type and optional parameters2012 - C# 5.0released with .NET 4.5 and VS2012Async programming, caller info attributes. Breaking change:loop variable closure.
HistorySummary8 Cool C# 6.0 FeaturesAgenda
1. Auto Property InitializersJoin the Conversation #DevSuperPowers @EricPhan
Currentlypublic class Developer{ public Developer() { DrinksCoffee = true; } public bool DrinksCoffee { get; set; }}C# 6.0public class Developer{ public bool DrinksCoffee { get; set; } = true;}Auto Property Initializers
Join the Conversation #DevSuperPowers @EricPhan
Auto Property InitializersPuts the defaults along with the declarationCleans up the constructorJoin the Conversation #DevSuperPowers @EricPhan
2. Dictionary Initializers
When I was a kidvar devSkills = new Dictionary();devSkills["C#"] = true;devSkills["VB.NET"] = true;devSkills["AngularJS"] = true;devSkills["Angular2"] = false;
Dictionary InitializersVS2013 C# 5.0var devSkills = new Dictionary(){ { "C#", true }, { "VB.NET", true }, { "AngularJS", true }, { "Angular2", false},};
VS2015 C# 6.0var devSkills = new Dictionary(){ ["C#"] = true, ["VB.NET"] = true, ["AngularJS"] = true, ["Angular2"] = false};
Join the Conversation #DevSuperPowers @EricPhan
Dictionary InitializersCleaner, less { and } to try and matchMore like how you would actually use a DictionarydevSkills["C#"] = true;
Join the Conversation #DevSuperPowers @EricPhan
3. String Interpolation
Bad:var firstName = "Eric";var lastName = "Phan";var jobTitle = "Chief Architect"; var company = "SSW";var display = firstName + " " + lastName + ", " + jobTitle + " @ " + company;
String InterpolationBest (C# 6.0):var firstName = "Eric";var lastName = "Phan";var jobTitle = "Chief Architect"; var company = "SSW";var display = $"{firstName} {lastName}, {jobTitle} @ {company}";
Better:var firstName = "Eric";var lastName = "Phan";var jobTitle = "Chief Architect"; var company = "SSW";var display = string.Format("{0} {1}, {3} @ {2}", firstName, lastName, company, jobTitle);
Join the Conversation #DevSuperPowers @EricPhan
String InterpolationMuch clearer as you can see what variables are being used inlineCan do formatting inline too{startDate:dd/MMM/yy}{totalAmount:c2}Join the Conversation #DevSuperPowers @EricPhan
4. Null Conditional Operator
public string[] GenerateCoffeeOrder(Coffee[] favCoffee){ var order = favCoffee.Select(x => $"{x.Name} - {x.Size}").ToArray(); return order;}Null Conditional OperatorWhats wrong with the above code?
public string[] GenerateCoffeeOrder(Coffee[] favCoffee){ if (favCoffee == null) { return null; } var order = favCoffee.Select(x => $"{x.Name} - {x.Size}").ToArray(); return order;}C# 6.0public string[] GenerateCoffeeOrder(Coffee[] favCoffee){ var order = favCoffee?.Select(x => $"{x.Name} - {x.Size}").ToArray(); return order;}Null Conditional OperatorFix by adding a null check
Join the Conversation #DevSuperPowers @EricPhan
Null Conditional Operator?.? If the variable is null, then return nullOtherwise execute whatever is after the .Similar to the ternary operation (conditional operator)var tax = hasGST ? subtotal * 1.1 : subtotal;Saves you many lines of null checking with just one simple character. Join the Conversation #DevSuperPowers @EricPhan
Null Conditional OperatorJoin the Conversation #DevSuperPowers @EricPhanpublic event EventHandler DevSuperPowerActivated;private void OnDevSuperPowerActivated(EventArgs specialPowers){ if (DevSuperPowerActivated != null) { DevSuperPowerActivated(this, specialPowers); }}
C# 6.0public event EventHandler DevSuperPowerActivated;private void OnDevSuperPowerActivated(EventArgs specialPowers){ DevSuperPowerActivated?.Invoke(this, specialPowers);}
5. nameOf Expression
nameOf ExpressionIn the previous example, it would probably be better to throw an exception if the parameter was nullJoin the Conversation #DevSuperPowers @EricPhanpublic string[] GenerateCoffeeOrder(Coffee[] favCoffee){ if (favCoffee == null) { throw new ArgumentNullException("favCoffee"); } var order = favCoffee.Select(x => $"{x.Name} - {x.Size}").ToArray(); return order;}
nameOf ExpressionWhats the problem?Refactor name change Change favCoffee to coffeeOrdersJoin the Conversation #DevSuperPowers @EricPhanpublic string[] GenerateCoffeeOrder(Coffee[] coffeeOrders){ if (coffeeOrders == null) { throw new ArgumentNullException("favCoffee"); } var order = coffeeOrders => $"{x.Name} - {x.Size}").ToArray(); return order;}Not Renamed!
nameOf Expression
Join the Conversation #DevSuperPowers @EricPhanC# 6.0public string[] GenerateCoffeeOrder(Coffee[] coffeeOrders){ if (coffeeOrders == null) { throw new ArgumentNullException(nameOf(coffeeOrders)); } var order = favCoffee.Select(x => $"{x.Name} - {x.Size}").ToArray(); return order;}
nameOf ExpressionGives you compile time checking whenever you need to refer to the name of a parameterJoin the Conversation #DevSuperPowers @EricPhan
6. Expression Bodied Functions & Properties
Join the Conversation #DevSuperPowers @EricPhanExpression Bodied Functions & PropertiesCurrentlypublic class Coffee { public string Name { get; set; } public string Size { get; set; } public string OrderDescription { get { return string.Format("{0} - {1}", Name, Size); } }}C# 6.0public class Coffee { public string Name { get; set; } public string Size { get; set; } public string OrderDescription => $"{Name} - {Size}";}
C# 6.0public class Coffee { public string Name { get; set; } public string Size { get; set; } public string OrderDescription => $"{Name} - {Size}";}Join the Conversation #DevSuperPowers @EricPhanExpression Bodied Functions & Propertiespublic class Coffee { name: string; size: string; orderDescription: () => string; constructor() { this.orderDescription = () => `${this.name} - ${this.size}`; }}TypeScriptWhat language is this?
Join the Conversation #DevSuperPowers @EricPhan7. Exception Filters
Currentlycatch (SqlException ex){ switch (ex.ErrorCode) { case -2: return "Timeout Error"; case 1205: return "Deadlock occurred"; default: return "Unknown"; }}C# 6.0catch (SqlException ex) when (ex.ErrorCode == -2){ return "Timeout Error";}catch (SqlException ex) when (ex.ErrorCode == 1205){ return "Deadlock occurred";}catch (SqlException) { return "Unknown";}
Exception Filters
Join the Conversation #DevSuperPowers @EricPhan
Exception FiltersGets rid of all the if statementsNice contained blocks to handle specific exception casesJoin the Conversation #DevSuperPowers @EricPhanHot Tip: Special peaceful weekends exception filter*catch (SqlException ex) when (HttpContext.Current.Identity.Name == "Boss Man" || DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday) { // Do nothing}
* Disclaimer: Dont do this
8. Static UsingJoin the Conversation #DevSuperPowers @EricPhan
C# 6.0using static System.Math;public double GetArea(double radius){ return PI * Pow(radius, 2);}
Currently
public double GetArea(double radius){ return Math.PI * Math.Pow(radius, 2);}
Static Using
Join the Conversation #DevSuperPowers @EricPhan
Static UsingGets rid of the duplicate static class namespaceCleaner codeLike using the With in VB.NETJoin the Conversation #DevSuperPowers @EricPhan
Theres more tooAwait in Catch and Finally BlocksExtension Add in Collection InitializersJoin the Conversation #DevSuperPowers @EricPhan
HistorySummary8 Cool C# 6.0 FeaturesAgenda
SummaryStart using these features now!VS 2013 + Install-Package Microsoft.Net.CompilersVS 2015 Out of the boxFor Build server Microsoft Build Tools 2015 or reference the NuGet Package
With all these goodiesYou should be 350% more productive at codingGet reminded about using these cool features with ReSharper
2 things...
@EricPhan #DevSuperPowersTweet your favourite C# 6.0 Feature
Join the Conversation #DevOps #NDCOslo @AdamCogan
Find me on Slideshare!http://www.slideshare.net/EricPhan6
Thank you!
info@ssw.com.auwww.ssw.com.auSydney | Melbourne | Brisbane | Adelaide
Recommended