Greetings I was doing some lazy initialization code today, and thought why not use the null-coalescing operator to do this, it is shorter, but then I thought is there any overhead or additional cost to doing it this way.
Below is simplified sample code showing a more common form used for lazy initialization, and then one using null-coalescing operator. They have the exact same results, and appear equivalent. My first thoughts are that after the object has been created there is now an additional assignment of it to itself using ??
. Is this a non-issue and the compiler/JIT optimizes this some how, is there something more nefarious going on and you should never do lazy initialization with ??
, or it is perfectly safe and no bad mojo can come from it.
private MyLazyObject _lazyObject;
public MyLazyObject GetMyLazyObjectUsingMoreCommonMethod()
{
if (_lazyObject != null)
return _lazyObject;
_lazyObject = new MyLazyObject();
return _lazyObject;
}
public MyLazyObject GetMyLazyObjectUsingNullCoalescingOpMethod()
{
_lazyObject = _lazyObject ?? new MyLazyObject();
return _lazyObject;
}
return _lazyObject ?? (_lazyObject = new MyLazyObject());
Is that still readable? YMMV. – Saddlebackif(_lazyObj == null) _lazyObj = new MyLazyObj(); return _lazyObj;
, it will be both more readable and shorter. – Feoffeereturn _lazyObject ?? new MyLazyObject());
– Wamplerreturn _lazyObject ??= new MyLazyObject();
– Gallman