Writing Better C# Using C# 6 By: Mitchel Sellers
About Your Speaker Mitchel Sellers CEO/Director of Development of IowaComputerGurus, Inc Microsoft C# MVP DNN MVP Contact Information Blog:
Agenda Quick History of C# C# 6 Mind Blowing? Or “Just Fluff”? Feature Listing & Detail
Quick History of C# C# 1:.NET 1.0 C# 1.2:.NET 1.1 C# 2:.NET 2.0 Generics C# 3:.NET 3 & 3.5 Auto-Properties Extension Methods Anonymous Types C# 4:.NET 4 Named & Optional Args C# 5:.NET 4.5 Async!
C# 6 Mind Blowing? Or Just “Fluff” Compiler as a Service? What does Rosyln Mean to you? Hidden features? Visual Studio Support & Extension Tooling? Can you use C# 6 features when targeting <.NET 4.6? What do you use?
using static Adds an ability to import static classes via a using statement Simply coding operations when working with math, files, console, etc Math Example var result = System.Math.Pow(5, 7); // Old Way using static System.Math; var result = Pow(5,7); Intellisense still shows rooting: Far more powerful with other classes using static System.Console using static System.IO.Directory Can be used with older.NET Runtimes
nameof() Simply & Standardize reporting of errors & notifications Better implementation IPropertyChanged Improved argument reporting throw new ArgumentException("Oops!", nameof(myValue)); Supports automatic refactoring within the VS tooling Can be used on older.NET runtimes
String Interpolation Better way of formatting strings Old way String.Format(“Oops {0} isn’t valid”, name); New way $”Ooops {name} isn’t valid” Can use backwards compatible (BUT!!! Only for standard, not the more complex iformattable string)
Null Conditional Operator (?.) Allows you to short-circuit calls to prevent nexting Examples int? nameLength = Person?.Name?.Length Only executes the next portion in the chain if not null If person is null returns null & short circuits If name is null returns null & short circuits Else returns length Great for invoking a method Can be used with prior.NET languages
Expression Bodied Properties & Methods The ability to inline/create methods & properties with lambdas! Property Example public static string MyConfigValue => ConfigurationManager.AppSettings["Test"]; Method Example public static void LogError(string errorMsg) => Console.WriteLIne(errorMsg); Can be used with prior runtimes!
Auto Property Initializers & Getters Lets you set the values as needed when you create properties Example public string FirstName { get; set; } = "Mitch"; public string LastName { get; } = “Sellers”; Can be used on older.NET version
Exception Filters