CSharp6Features.cs
using static System.Linq.Enumerable; //C# 6: "using static"
using static System.Math;
using static System.DayOfWeek;
using static System.String;
using System.Collections.Generic;
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
class Program
{
public static void Main()
{
FormattingAndStringInterpolation ();
IndexInitializers ();
UsingStatic ();
ExceptionFiltersAndNameof ("1.2", "notADate", "1");
ExceptionFiltersAndNameof ("notAFloat", "2015-01-01", "1");
AutoPropertyInitializersAndExpressionBodiedMembers ();
AsyncExceptions ();
}
/*
* C# 6: String interpolation and formatting
* (Note that string interpolation is used throughout program)
*/
public static void FormattingAndStringInterpolation()
{
var values = new int[] { 1, 2, 3, 4, 12, 123456 };
// String interpolation and formatting
foreach (var s in values.Select (i => $"The value is { i,10:N2}.")) {
Console.WriteLine (s);
}
// String interpolation works with expressions, not just variables
Console.WriteLine($"Minimum is { values.Min(i => i):N2}.");
}
/*
* C# 6: index initializers, null-conditional operator
*/
public static void IndexInitializers()
{
var rnd = new Random ();
// String interpolation
Func<DayOfWeek, ToDo> fnWithNulls = (dow) => rnd.NextDouble() > 0.4 ? new ToDo (rnd.NextDouble() > 0.4 ? $"Study C# 6 on {dow}" : null) : null;
// Index initializer
var dict = new Dictionary<DayOfWeek, ToDo> {
[ DayOfWeek.Monday ] = fnWithNulls( DayOfWeek.Monday ),
[ DayOfWeek.Tuesday ] = fnWithNulls ( DayOfWeek.Tuesday ),
[ DayOfWeek.Wednesday ] = fnWithNulls ( DayOfWeek.Wednesday ),
[ DayOfWeek.Thursday ] = fnWithNulls ( DayOfWeek.Thursday ),
[ DayOfWeek.Friday ] = fnWithNulls ( DayOfWeek.Friday ),
[ DayOfWeek.Saturday ] = fnWithNulls ( DayOfWeek.Saturday ),
[ DayOfWeek.Sunday ] = fnWithNulls ( DayOfWeek.Sunday )
};
foreach (var key in dict.Keys) {
// Null-conditional operator (nested) and string interpolation (and C# 5 null-coalescing operator)
System.Console.WriteLine ($"\"{dict[key]?.Description}\": A string of length {dict [key]?.Description?.Length ?? 0} ");
}
}
/*
* C# 6: using static -- Math, String, Enumerable
*/
public static void UsingStatic()
{
// using static with static function Math.Cos (but not const Math.PI)
for (var angle = 0.0; angle <= Math.PI / 2; angle += Math.PI / 8) {
System.Console.WriteLine ($"Cos({angle:N2}) radians = {Cos(angle):N2}");
}
// using static with extension functions (Enumerable functions available, but not whole System.Linq namespace)
var evenStrings = Range(0,100).Where (i => i % 2 == 0).Select(i => i.ToString());
// using static with String.Join
var outputString = Join (", ", evenStrings);
System.Console.WriteLine (outputString);
}
/*
* C# 6: Exception filter and nameof
*/
public static void ExceptionFiltersAndNameof(string aFloat, string date, string anInt)
{
try
{
var f = Double.Parse(aFloat);
var d = DateTime.Parse(date);
var n = Int32.Parse(anInt);
// Exception filter
}catch(FormatException e) when (e.Message.IndexOf("DateTime") > -1)
{
// nameof
Console.WriteLine($"Problem parsing \"{nameof(date)}\" argument");
}catch(FormatException x)
{
Console.WriteLine("Problem parsing some other argument");
}
}
/*
* C# 6 : Auto-property initializers and expression-bodied members are used in ToDo class defined below
*/
public static void AutoPropertyInitializersAndExpressionBodiedMembers()
{
// class ToDo demonstrates auto-property initializers and expression-bodied members
var todo = new ToDo ("Something");
}
/*
* C# 6 : await in catch and finally are demonstrated in AsyncMethod() defined below
*/
public static void AsyncExceptions()
{
var factory = new TaskFactory ();
var myResult = factory.StartNew<Task<int>> (AsyncMethod).Unwrap ().GetAwaiter ().GetResult ();
System.Console.WriteLine ($"The answer is {myResult}");
}
public static async Task<int> AsyncMethod()
{
List<AsyncResource> resources = new List<AsyncResource>();
try{
var creationTasks = Range(0,10).Select(async _ => await AsyncResource.CreateAsync());
foreach(var creationTask in creationTasks)
{
var resource = await creationTask;
resources.Add(resource);
await AsyncResource.LogAsync($"Resource.Id[{resource.Id}]: Normal course of behavior");
resource.ExceptionThrowingFunction();
}
}catch(Exception x) {
// await in exception-handler
await AsyncResource.LogAsync ($"Exception thrown {x.Message}");
}finally{
// await in finally
foreach (var resource in resources) {
await resource.FinalizeAsync ();
}
}
System.Console.WriteLine ("Execution complete");
return 42;
}
}
/*
* Class demonstrates initializers, expression-bodied members, and string interpolation
*/
class ToDo
{
// Auto-property initializers
public DateTime Due { get; set; } = DateTime.Now.AddDays(1);
// Getter-only auto-property
public DateTime Created { get; } = DateTime.Now;
// Getter-only auto-property with assignment in constructor
public string Description { get; }
public ToDo (string description)
{
// Constructor-only assignment to getter-only auto-property
this.Description = description;
}
//Expression-bodied members and string interpolation
public override string ToString() => $"{Description}: Due {Due}";
}
/*
* Class is randomly asynchronous and throws exceptions.
* Demonstrates getter-only auto-properties and is used to demonstrate await in catch and finally
*/
public class AsyncResource
{
private static int count = 0;
private static Random rand = new Random();
public int Id { get; } = AsyncResource.count++;
public static async Task<AsyncResource> CreateAsync()
{
await Task.Delay (rand.Next(30) * 100);
var r = new AsyncResource ();
LogAsync ($"Created Resource.Id[{r.Id}]");
return r;
}
public static async Task LogAsync(string msg)
{
var timeReceived = DateTime.Now;
await Task.Delay(rand.Next(30) * 100);
System.Console.WriteLine($"{timeReceived.ToString("mm:ss.fff tt")}: {msg}");
}
public async Task FinalizeAsync()
{
await Task.Delay (rand.Next(30) * 100);
System.Console.WriteLine ($"Finalizing Resource.Id[{Id}]");
}
public void ExceptionThrowingFunction()
{
if(rand.NextDouble() < Id / 10.0)
{
throw new Exception ($"Resource.Id[{Id}] goes Boom!");
}
}
}
Let us know how you feel about this.
0/250
Thanks for the feedback!
Xamarin Workbook
If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.