C# - null coalescing operator (??)
The null coalescing operator in C# is represented by ??
. It is used to provide a default value for nullable value types and reference types, helping to avoid null reference exceptions in your code.
Here's a simple example to illustrate how the null coalescing operator works:
using System;
class NullCoalescingExample
{
static void Main()
{
// Nullable int with a value
int? numberWithAValue = 10;
// Nullable int without a value (null)
int? nullNumber = null;
// Using the null coalescing operator
int result1 = numberWithAValue ?? 0;
int result2 = nullNumber ?? -1;
// Displaying results
Console.WriteLine("Result 1 (non-null value): " + result1); // Outputs 10
Console.WriteLine("Result 2 (null value): " + result2); // Outputs -1
}
}
In this code:
- We have two nullable integers (
int?
). One is assigned a value (10
), and the other is null
.
- We then use the null coalescing operator to set
result1
and result2
. If the nullable integer has a value, that value is used. If it is null
, the operator returns the value provided after ??
.
- So,
result1
becomes 10
(as numberWithAValue
has a value), and result2
becomes -1
(as nullNumber
is null
).
The output of this program will be:
Result 1 (non-null value): 10
Result 2 (null value): -1
This example demonstrates how the null coalescing operator can simplify handling null values and provide default values when needed.
- Purpose: The null coalescing operator (`??`) is used to handle situations where a value might be null, and we want to provide a default value if it is indeed null.
- Nullable Values: It works with both nullable value types (like `int?`, `double?`) and reference types (like strings).
- Syntax: The operator consists of two question marks (`??`) placed between the nullable value and the default value.
- Checking for Null: It checks if the left-side value is null. If it's not null, it returns that value. If it is null, it returns the right-side default value.
- Avoiding Null Reference Exceptions: It's a handy tool to prevent null reference exceptions, which can crash your program when you try to access properties or methods on null objects.
- Default Values: You can set any value as the default, whether it's a number, string, or even another variable.
- Use Cases: Common use cases include providing default values for user inputs, database queries, or configuration settings.
- Simplified Code: It simplifies code by reducing the need for explicit null checks and conditional statements.
- Example: In `int? number = null; int result = number ?? 5;`, if `number` is null, `result` will be set to `5`.
- Chaining: You can chain multiple null coalescing operators together to handle nested null values.