Concept Flow - Null-coalescing operator
Evaluate left expression
Is left null?
No→Use left value
Yes
Use right expression value
The null-coalescing operator checks if the left value is null; if not, it uses it, otherwise it uses the right value.
string name = null; string displayName = name ?? "Guest"; Console.WriteLine(displayName);
| Step | Expression Evaluated | Value | Is Null? | Result Used |
|---|---|---|---|---|
| 1 | name | null | Yes | Evaluate right expression |
| 2 | "Guest" | "Guest" | - | Use "Guest" |
| 3 | displayName assigned | "Guest" | - | - |
| 4 | Console.WriteLine(displayName) | "Guest" | - | Output: Guest |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| name | null | null | null | null |
| displayName | unassigned | unassigned | "Guest" | "Guest" |
Null-coalescing operator (??) returns the left value if not null; otherwise, it returns the right value. Syntax: var result = left ?? right; Use it to provide default values when a variable might be null. It evaluates right only if left is null. Commonly used to avoid null checks.
What does the null-coalescing operator ?? do in C#?
?? is used to provide a fallback value when the left-hand side is null.Which of the following is the correct syntax to use the null-coalescing operator in C#?
string name = null; string displayName = ??? "Guest";
left ?? right, where right is the fallback value.string displayName = name ?? "Guest";, it correctly assigns "Guest" if name is null.What will be the output of the following C# code?
string input = null; string result = input ?? "Default"; Console.WriteLine(result);
inputinput is assigned null.input ?? "Default" returns "Default" because input is null.Identify the error in the following code snippet using the null-coalescing operator:
int? number = null; int result = number ?? null; Console.WriteLine(result);
number is nullable int (int?), but result is non-nullable int.null, which cannot be assigned to non-nullable int result.Given the following code, what will be the output?
string? firstName = null; string? lastName = "Smith"; string fullName = firstName ?? lastName ?? "Unknown"; Console.WriteLine(fullName);
firstName is null, so firstName ?? lastName evaluates to lastName, which is "Smith".lastName is not null, the second ?? "Unknown" is not used.Pass the test and this pattern moves unknown