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 ?? .
source share