Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorthand way to return values that might be null?

How can I write a shorthand of the following scenario?

get {     if (_rows == null)     {         _rows = new List<Row>();     }      return _rows; } 
like image 599
ErrorAgain Avatar asked Jul 08 '16 12:07

ErrorAgain


People also ask

Is null shortcut C#?

The null-coalescing operator ( ?? ) is like a shorthand, inline if/else statement that handles null values. This operator evaluates a reference value and, when found non-null, returns that value. When that reference is null , then the operator returns another, default value instead.

IS NOT NULL in if Condition C#?

In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.


1 Answers

Using null-coalescing operator ( ?? ):

get  {       _rows = _rows ?? new List<Row>();       return _rows;  } 

OR (less readable):

get { return _rows ?? (_rows = new List<Row>()); } 

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

like image 185
Zein Makki Avatar answered Sep 23 '22 05:09

Zein Makki