Home > Article > Backend Development > What operators does C# provide to handle null values?
C# has the following three operators to handle null values -
allows you to get the value of a variable (if not) null, or specify a default value that can be used.
It replaces the following expression in C# -
string resultOne = value != null ? value : "default_value";
with the following expression -
string resultTwo = value ?? "default_value";
Here is an example illustrating this.
Example
using System; class Program{ static void Main(){ string input = null; string choice = input ?? "default_choice"; Console.WriteLine(choice); // default_choice string finalChoice = choice ?? "not_chosen"; Console.WriteLine(finalChoice); // default_choice } }
If the value on the left is not null, return the value. Otherwise, it returns the value on the right. In other words, it allows you to initialize a variable to some default value if its current value is null.
It replaces the following expression in C# -
if (result == null) result = "default_value";
Use the following expression.
result ??= "default_value";
This operator is useful for lazily computed properties. For example -
Example
class Tax{ private Report _lengthyReport; public Report LengthyReport => _lengthyReport ??= CalculateLengthyReport(); private Report CalculateLengthyReport(){ return new Report(); } }
This operator allows you to safely call methods on an instance. If the instance is null, return null instead of throwing a NullReferenceException. Otherwise, it just calls the method.
It replaces the following expression in C# -
string result = instance == null ? null : instance.Method();
Use the following expression -
string result = instance?.Method();
Consider the following example.
Example
using System; string input = null; string result = input?.ToString(); Console.WriteLine(result); // prints nothing (null)
Real-time demonstration
using System; class Program{ static void Main(){ string input = null; string choice = input ?? "default_choice"; Console.WriteLine(choice); // default_choice string finalChoice = choice ?? "not_chosen"; Console.WriteLine(finalChoice); // default_choice string foo = null; string answer = foo?.ToString(); Console.WriteLine(answer); // prints nothing (null) } }
default_choice default_choice
The above is the detailed content of What operators does C# provide to handle null values?. For more information, please follow other related articles on the PHP Chinese website!