Florian Rappl, MVP Visual C#
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#
""
@""
$""
System.FormattableString
in conjunction withSystem.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}.");
when
await
in catch
-blockspublic 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;
}
}
public String FileName { get; };
public Int32 AnswerToEverything => 42;
public static Double Arcosh(Double x) =>
Math.Log(x + Math.Sqrt(x * x - 1.0));
using static
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)}")
};
}
}
nameof
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();
}