Abbreviation for creating a new instance if null?

In Javascript, I can do this:

var myVar = returnNull() || new MyObject();

In C #, I do this:

 var myVar = returnObjectOrNull(); if (myVar == null) myVar = new MyObject(); 

Is there a way to shorten it to C #?

+4
source share
5 answers

use ?? operator

 foo ?? new Foo(); 

Or in your case

 var myVar = returnObjectOrNull() ?? new MyObject(); 

The operator is called the null coalescing operator and is used to determine the default value for NULL value types or reference types. This returns the left operand if the operand is not equal to zero; otherwise returns the right operand.

+20
source

Use a null-bound operator :

 var myvar = returnObjectOrNull() ?? new MyObject(); 
+2
source

Use the zero coalescing operator

 var myVar = returnObjectOrNull(); myVar = myVar ?? new MyObject(); 
+2
source

Yes, this is called the null coalescing operator :

 var myVar = returnObjectOrNull() ?? new MyObject(); 

Note that this statement will not evaluate the right side if the left side is not zero, which means that the above line of code will not create a new MyObject if it is not needed.

Here is a LINQPad example to demonstrate:

 void Main() { var myVar = returnObjectOrNull() ?? new MyObject(); } public MyObject returnObjectOrNull() { return new MyObject(); } public class MyObject { public MyObject() { Debug.WriteLine("MyObject created"); } } 

This will lead to the output of "MyObject created" once, which means that only one object is created in the returnObjectOrNull method, and not in the statement line ?? .

+1
source

Can you use ?? Operator (C# Reference) ?? Operator (C# Reference) , for example:

 var myVar = returnObjectOrNull() ?? new MyObject(); 

Operator ?? is called the null coalescing operator and is used to determine the default value for NULL value types or reference types. This returns the left operand if the operand is not equal to zero; otherwise returns the right operand.

0
source

Source: https://habr.com/ru/post/1484841/


All Articles