???? et ?? =, opérateurs (référence C#)and ??= operators (C# reference)
L’opérateur de fusion null ??
retourne la valeur de l’opérande de gauche si elle n’est pas null
; sinon, il évalue l’opérande de droite et retourne son résultat.The null-coalescing operator ??
returns the value of its left-hand operand if it isn't null
; otherwise, it evaluates the right-hand operand and returns its result. L’opérateur ??
n’évalue pas son opérande droit si l’opérande gauche a la valeur non null.The ??
operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.
Disponible en C# 8,0 et versions ultérieures, l’opérateur d’assignation de fusion Null ??=
affecte la valeur de son opérande droit à son opérande de gauche uniquement si l’opérande de gauche est évalué à null
.Available in C# 8.0 and later, the null-coalescing assignment operator ??=
assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null
. L’opérateur ??=
n’évalue pas son opérande droit si l’opérande gauche a la valeur non null.The ??=
operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.
List<int> numbers = null;
int? a = null;
(numbers ??= new List<int>()).Add(5);
Console.WriteLine(string.Join(" ", numbers)); // output: 5
numbers.Add(a ??= 0);
Console.WriteLine(string.Join(" ", numbers)); // output: 5 0
Console.WriteLine(a); // output: 0
L’opérande gauche de l' ??=
opérateur doit être une variable, une propriétéou un élément d' indexeur .The left-hand operand of the ??=
operator must be a variable, a property, or an indexer element.
En C# 7,3 et versions antérieures, le type de l’opérande gauche de l' ??
opérateur doit être un type référence ou un type valeur Nullable.In C# 7.3 and earlier, the type of the left-hand operand of the ??
operator must be either a reference type or a nullable value type. À compter de C# 8,0, cette spécification est remplacée par ce qui suit : le type de l’opérande gauche des ??
opérateurs et ??=
ne peut pas être un type valeur non Nullable.Beginning with C# 8.0, that requirement is replaced with the following: the type of the left-hand operand of the ??
and ??=
operators cannot be a non-nullable value type. En particulier, à compter de C# 8,0, vous pouvez utiliser les opérateurs de fusion Null avec des paramètres de type sans contrainte :In particular, beginning with C# 8.0, you can use the null-coalescing operators with unconstrained type parameters:
private static void Display<T>(T a, T backup)
{
Console.WriteLine(a ?? backup);
}
Les opérateurs de fusion Null sont associatifs à droite.The null-coalescing operators are right-associative. Autrement dit, les expressions de la formeThat is, expressions of the form
a ?? b ?? c
d ??= e ??= f
sont évaluées commeare evaluated as
a ?? (b ?? c)
d ??= (e ??= f)
ExemplesExamples
Les ??
??=
opérateurs et peuvent être utiles dans les scénarios suivants :The ??
and ??=
operators can be useful in the following scenarios:
Dans les expressions avec les opérateurs conditionnels null ?. et ? [], vous pouvez utiliser l'
??
opérateur pour fournir une autre expression à évaluer au cas où le résultat de l’expression avec des opérations conditionnelles null estnull
:In expressions with the null-conditional operators ?. and ?[], you can use the??
operator to provide an alternative expression to evaluate in case the result of the expression with null-conditional operations isnull
:double SumNumbers(List<double[]> setsOfNumbers, int indexOfSetToSum) { return setsOfNumbers?[indexOfSetToSum]?.Sum() ?? double.NaN; } var sum = SumNumbers(null, 0); Console.WriteLine(sum); // output: NaN
Quand vous utilisez des types valeur Nullable et que vous devez fournir une valeur d’un type valeur sous-jacent, utilisez l'
??
opérateur pour spécifier la valeur à fournir dans le cas où une valeur de type Nullable estnull
:When you work with nullable value types and need to provide a value of an underlying value type, use the??
operator to specify the value to provide in case a nullable type value isnull
:int? a = null; int b = a ?? -1; Console.WriteLine(b); // output: -1
Utilisez la méthode Nullable<T>.GetValueOrDefault() si la valeur à utiliser quand une valeur de type Nullable est
null
doit être la valeur par défaut du type valeur sous-jacent.Use the Nullable<T>.GetValueOrDefault() method if the value to be used when a nullable type value isnull
should be the default value of the underlying value type.À compter de C# 7,0, vous pouvez utiliser une
throw
expression comme opérande de droite de l'??
opérateur pour rendre le code de vérification d’argument plus concis :Beginning with C# 7.0, you can use athrow
expression as the right-hand operand of the??
operator to make the argument-checking code more concise:public string Name { get => name; set => name = value ?? throw new ArgumentNullException(nameof(value), "Name cannot be null"); }
L’exemple précédent montre également comment utiliser des membres expression-bodied pour définir une propriété.The preceding example also demonstrates how to use expression-bodied members to define a property.
À compter de C# 8,0, vous pouvez utiliser l'
??=
opérateur pour remplacer le code du formulaire.Beginning with C# 8.0, you can use the??=
operator to replace the code of the formif (variable is null) { variable = expression; }
par le code suivant :with the following code:
variable ??= expression;
Capacité de surcharge de l’opérateurOperator overloadability
Les opérateurs ??
et ??=
ne peuvent pas être surchargés.The operators ??
and ??=
cannot be overloaded.
spécification du langage C#C# language specification
Pour plus d’informations sur l' ??
opérateur, consultez la section opérateur de fusion Null de la spécification du langage C#.For more information about the ??
operator, see The null coalescing operator section of the C# language specification.
Pour plus d’informations sur l' ??=
opérateur, consultez la Remarque relativeà la proposition de fonctionnalité.For more information about the ??=
operator, see the feature proposal note.