Page 199 - CSharp/C#
P. 199
Console.WriteLine($"String has {$"My class is called {nameof(MyClass)}.".Length} chars:");
Console.WriteLine($"My class is called {nameof(MyClass)}.");
Output:
String has 27 chars:
My class is called MyClass.
Await in catch and finally
It is possible to use await expression to apply await operator to Tasks or Task(OfTResult) in the
catch and finally blocks in C#6.
It was not possible to use the await expression in the catch and finally blocks in earlier versions
due to compiler limitations. C#6 makes awaiting async tasks a lot easier by allowing the await
expression.
try
{
//since C#5
await service.InitializeAsync();
}
catch (Exception e)
{
//since C#6
await logger.LogAsync(e);
}
finally
{
//since C#6
await service.CloseAsync();
}
It was required in C# 5 to use a bool or declare an Exception outside the try catch to perform async
operations. This method is shown in the following example:
bool error = false;
Exception ex = null;
try
{
// Since C#5
await service.InitializeAsync();
}
catch (Exception e)
{
// Declare bool or place exception inside variable
error = true;
ex = e;
}
// If you don't use the exception
if (error)
{
https://riptutorial.com/ 145

