http://itsnull.com/presentations/csharp6/
Created by Kip Streithorst / @itsnull
Click on links for MSDN documentation
//C# 6
using static System.Console;
using static System.ConsoleColor; //enumeration
using static System.Math;
void Calculate(double value) {
ForegroundColor = Blue;
WriteLine("Result is " + Sqrt(value));
}
//C# 5
using System;
void Calculate(double value) {
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Result is " + Math.Sqrt(value));
}
Add when (expression) to end of a catch clause. Exception is caught only if expression is true.
//C# 6
try {
//...
} catch (ArgumentException e) when (e.ParamName == "creditCard") {
abortSale();
}
//C# 5
try {
//...
} catch (ArgumentException e)
if (e.ParamName == "creditCard")
abortSale();
else
throw; //re-throw changes stack-trace
}
//C# 6
try {
//...
} catch (Exception e) when (LogException(e)) {}
//C# 5
try {
//...
} catch (Exception e) {
LogException(e);
throw;
}
//C# 6
async Task ProcessData() {
try {
await UpdateRecord();
} catch (Exception e) {
await LogException(e); //compile error in C# 5, now works
} finally {
await NotifySubscribers(); //compile error in C# 5, now works
}
}
new TestObj { [index] = value, [index2] = value2 }
//C# 6
var numbers = new Dictionary<int, string> {
[7] = "seven",
[13] = "thirteen"
};
numbers[8] = "eight";
//C# 5
var numbers = new Dictionary<int, string> {
{7, "seven"}
{13, "thirteen"}
};
numbers[8] = "eight";
//C# 6
void TestMethod(Customer person) {
string name = person.FirstName; //might throw NullPointerException
string name2 = person?.FirstName;
int? age = person?.Age; //Age is int
bool? inUs = person?.Address?.IsInUS(); //IsInUs() method returns bool
string recentOrder = person?.Orders?[0]?.OrderId;
//throws IndexOutOfRangeException if Orders is non-null but empty
}
//C# 6
var zip = person?.Address?.ZipCode ?? "Unknown Zip";
//C# 5
var zip = "Unknown Zip";
var tempPerson = person;
if (tempPerson != null)
var tempAddress = tempPerson.Address;
if (tempAddress != null)
zip = tempAddress.ZipCode ?? "Unknown Zip";
Returns a string, which is the unqualified name of a variable, type or member.
//C# 6
void TestMethod(Customer person) {
nameof(person); // variable - returns "person" - variable
nameof(person.Address.ZipCode); // member - returns "ZipCode"
nameof(System.DateTime); // type - returns "DateTime"
nameof(System.Collections.Generic.List<int>); // type - returns "List"
}
In-line template strings, use $"" instead of "" where {expression} is replaced with the ToString representation.
//C# 6
void Format(string name, DateTime startDate, double salary) {
string tag = $"{name}, hired {startDate:D}";
string wage = $"Paid: {salary:c}";
string desc = $"Is {(startDate.Year < 2010 ? "pre" : "post")} reorg";
}
//C# 5
void Format(string name, DateTime startDate, double salary) {
string tag = String.Format("{0}, hired {1:D}", name, startDate);
string wage = String.Format("Paid: {0:c}", salary);
string desc = String.Format("Is {0} reorg",
(startDate.Year < 2010 ? "pre" : "post"));
}
//C# 6
static string Format(DateTime day) {
System.FormattableString temp = $"Modified {day:d}";
return temp.ToString(CultureInfo.GetCultureInfo("de-DE"));
}
Format(new DateTime(2012, 3, 15)); //returns "15.03.2012"
Example: Read-only computed property.
//C# 6
string FullName => First + " " + Last;
//C# 5
string FullName
{
get
{
return First + " " + Last;
}
}
Example: Method that immediately returns a value.
//C# 6
double ConvertCtoF(double temp) => (temp * 9/5) + 32;
//C# 5
double ConvertCtoF(double temp)
{
return (temp * 9/5) + 32;
}
Example: Single line void method.
//C# 6
void Log() => Console.WriteLine(First + " " + Last);
//C# 5
void Log()
{
Console.WriteLine(First + " " + Last);
}
Example: Read-only indexer.
//C# 6
Customer this[long id] => store.LookupCustomer(id);
//C# 5
Customer this[long id]
{
get
{
return store.LookupCustomer(id);
}
}
//C# 6
public string FullName { get; }; //read-only
public string FirstName { get; set; }; //read-write
//C# 5
public string FullName { get; private set; }; //read-only
public string FirstName { get; set; }; //read-write
//C# 6
public List<Address> Addresses { get; set; } = new List<Address>();
//works for read-only properties as well
public DateTime Created { get; } = DateTime.UtcNow;