Opérateurs
Apparence
Opérateur de fusion null (null-coalescing) ??
string s = s1 ?? s2;
// équivaut à
string s = s1 != null ? s1 : s2;
|
Opérateur conditionnel null (null-conditional) ?.
Opérateur ?. test si l'objet est null
- si oui retourne null
- sinon retourne la valeur de la propriété
string nom = personne?.Nom;
// équivalent de
string nom = personne != null ? personne.Nom : null;
// pour les types valeur la version nullable est renvoyée
int? age = personne?.Age; // si personne est null, retourne null
int age = personne?.Age ?? 0;
// invoking delegates in a thread-safe way with much less code
// code de OnPropertyChanged
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
// remplacé par
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName))
|
XOR
bool a = true;
bool b = false;
Console.WriteLine(a ^ a); // False
Console.WriteLine(a ^ b); // True
Console.WriteLine(b ^ b); // False
|
Conversion
Money m = new Money(42.42M);
decimal amount = m; // convertion implicite
int truncatedAmount = (int)m; // convertion explicite
class Money
{
public decimal Amount { get; set; }
public Money(decimal amount)
{
Amount = amount;
}
public static implicit operator decimal(Money money)
{
return money.Amount;
}
public static explicit operator int(Money money)
{
return (int)money.Amount;
}
}
|