Adam Pedley Adam Pedley -4 years ago 194
C# Question

Checking for nullable lazy value

If I have a Lazy value defined such as

Lazy<MyObject> _lazyObject = new Lazy<MyObject>();


If I want to check the value of this isn't null, before I call a method, which option should I do?

if (_lazyObject.IsValueCreated && _lazyObject.Value.Handle == IntPtr.Zero)
{
return false;
}

return _lazyObject.Value.MyMethod();


or

return _lazyObject?.Value?.MyMethod() ?? false;


I am preferring the second option because I think it accounts for the slight possibility that the Lazy object may become null between when it gets a handle, and when it makes the call. Is this a correct assumption?

Answer Source

From the question it is unclear what the problem is you're actually trying to solve. _lazyObject.Value should never be null unless you're providing a factory into the constructor that returns null.

For example

var lazy = new Lazy<string>(() => null);

var isNull = lazy.Value == null; // isNull is true

If Lazy<> is being used correctly you shouldn't need to check for null, you just use the value and whatever thread gets there first creates the value. Checking IsValueCreated will tell you if the value has been created yet, but I don't know why you would need to know this.

Generally the field/property holding the Lazy<> should be made readonly as you don't want to have multiple instances.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download