Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1) async / await
Use the async / await-pattern to allow unblocking of the UI / current thread when
execution blocking operations. The async / await-pattern works by letting the code
continue executing even if something is blocking the execution (like a web
request).
var defaultValue = 23
//NewWay
var someString = $"Some data: {someVariable}, some more data: {someOtherVariable}";
You can put C# expressions in between the braces, which makes this very powerful.
6) ?. (Null-conditional operator) - C# 6
The null-conditional operator works like this:
//Null if customer or customer.profile or customer.profile.age is null
var currentAge = customer?.profile?.age;
No more NullReferenceExceptions!
//...
}
This is how you should use it...
public void PrintUserName(User currentUser)
{
//The refactoring tool will not miss this...
if(currentUser == null)
_logger.Error($"Argument {nameof(currentUser)} is not provided");
//...
}
Read more about the nameof-expression here: https://msdn.microsoft.com/en-
us/library/dn986596.aspx
8) Property Initializers - C# 6
Property initializers lets you declare an initial value for a property:
public class User
{
public Guid Id { get; } = Guid.NewGuid();
// ...
}
A benefit of using property initializers is that you can not declare a set:er, thus
making the property immutable. Property initializers works great together with C# 6
primary constructor syntax.
9) as and is-operators
The is-operator is used to control if an instance is of a specific type, e.g. if
you want to see if a cast is possible:
if (Person is Adult)
{
//do stuff
}
Use the as-operator to try to cast an instance to a class. It will return null if
cast was not possible:
SomeType y = x as SomeType;
if (y != null)
{
//do stuff
}
10) yield-keyword
The yield-keyword lets you feed an an IEnumerable-interface with items. The
following example will return each powers of 2 up to the exponent of 8 (e.g. 2, 4,
8, 16, 32, 64, 128 ,256):
public static IEnumerable<int> Power(int number, int exponent)
{
int result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * number;
yield return result;
}
}
yield return can be very powerful if it's used in the correct way. It enables you
to lazily generate a sequence of objects, ie. the system does not have to enumerate
the whole collection - it can be done on demand.