C# 6 in 30 Minutes

Florian Rappl, MVP Visual C#

C# 6

in 30 Minutes

C# 6 Cover

Florian Rappl

Writer and consultant

  • Microsoft C# MVP and CodeProject MVP
  • Active contributions to open-source projects
  • Company workshops, talks and IT consulting

Languages and technologies

  • C#, JavaScript and C/C++
  • Full web stack (client and server)
  • High Performance and Embedded Computing
C# 6
Mads Torgersen
C# 6.0 adds about a dozen bite-sized new features to C#, all aimed at making your code cleaner and clearer.

Mads Torgersen
Program Manager for C#

Agenda

  1. Strings
  2. Exceptions
  3. Properties / Methods
  4. Initialization
  5. Elvis

What's new for strings?

  • Introducing string interpolation yields
    • Ordinary strings ""
    • Literal strings @""
    • Interpolated strings $""
  • Parts of the interpolation requires a new class
  • But we can easily provide our own implementation, e.g.,
    • System.FormattableString in conjunction with
    • System.Runtime.CompilerServices.FormattableStringFactory
    • FormattableString Create(string, params object[])
var number = 31;
 
var a = $"We can also compute stuff {5 * 8 + number}!";
 
var b = $"Using formatters is possible, like {number:X2}!";
 
var c = System.FormattableString.Invariant(
               $"Printing invariant PI: {Math.PI}.");

Catch less!

  • Exception filtering with when
  • Now we can await in catch-blocks
public static async Task<String> ReadFileAsync(this String fn) {
	try
	{
		using (var fs = File.OpenRead(fn))
		{
			using (var sr = new StreamReader(fs))
				return await sr.ReadToEndAsync();
		}
	}
	catch (PathTooLongException ex) when (fn.Length < 255)
	{
		await WriteExceptionToLogAsync(ex);
		return null;
	}
}

What's new for methods?

  • True readonly properties are now possible
  • Method expressions for convenience
  • Combine both for computed properties
public String FileName { get; };
 
public Int32 AnswerToEverything => 42;
 
public static Double Arcosh(Double x) =>
                     Math.Log(x + Math.Sqrt(x * x - 1.0));

Initialize all the things...

  • Make methods of atatic class available with using static
  • New index initializers for consistent object initialization
  • This new method works with any defined indexer
using static System.Math;
using static System.FormattableString;
 
public class Test {
	public String FileName { get; } = "my-file.txt";
 
	static Double Arcosh(Double x) => Log(x + Sqrt(x * x - 1.0));
 
	public static Dictionary<Double, String> CreateTable() {
		return new Dictionary<Double, String> {
			[1.0] = Invariant($"1.0 => {Arcosh(1.0)}"),
			[1.5] = Invariant($"1.5 => {Arcosh(1.5)}")
		};
	}
}

Elvis has left the building!

  • Resolve names using the nameof operator
  • probably the most important feature of C# 6: ?.
  • The so-called Elvis operator
  • Conditionally invoke member operator
public static void Change(this String str, Action<String> change) {
	var length = str?.Length ?? 0;
 
	if (length > 0)
		change?.Invoke(str);
}
public static void ShowTargetWindow(String target) {
	if (target == null)
		throw new ArgumentNullException(nameof(target));
 
	return Assembly.GetExecutingAssembly().GetTypes().
	           Where(m => m.Name == target).
	           Select(m => m.GetConstructor(null).Invoke(null)).
	           OfType<Window>().FirstOrDefault()?.Show();
}

Demo

Thanks for your attention

  • Feel free to contact me