What operators C# provides to deal with null values?



C# has the following three operators to deal with the null values −

null-coalescing operator (??)

Allows you to get the value of a variable if it's not null, alternatively specifying 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 that illustrates 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    } }

null-coalescing assignment operator (??=)

It returns the value on the left side if it's not null. Otherwise, it returns the value on the right side. 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";

with the following expression.

result ??= "default_value";

This operator is useful with lazily calculated properties. For example −

Example

class Tax{    private Report _lengthyReport;    public Report LengthyReport => _lengthyReport ??= CalculateLengthyReport();    private Report CalculateLengthyReport(){       return new Report();    } }

null-conditional operator (?.)

This operator allows you to call a method on an instance safely. If the instance is null, it returns null instead of throwing NullReferenceException. Otherwise, it simply calls the method.

It replaces the following expression in C# −

string result = instance == null ? null : instance.Method();

with 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)

Example

 Live Demo

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)    } }

Output

default_choice default_choice
Updated on: 2021-05-19T07:49:08+05:30

411 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements