I have a situation where I was using a ternary operator to determine whether or not an IEnumerable is null, and it was not behaving as I would expect.
If I do this:
var children = clickedItem.Children != null ? clickedItem.Children.ToArray() : null;
then I receive an argument null exception (“source cannot be null”) which indicates that the .ToArray() occurred despite the null check.
If I change this to (seemingly) identical logic:
var children = clickedItem.Children;
if (children != null) children = children.ToArray();
then the error disappears. Does the ternary operator not short-circuit as I always imagined it did?
EDIT Per the questions:
Yes, I am setting children the first time in, but not the second:
public IEnumerable<AlbumOrTrack> Children
{
get
{
if (_children == null)
{
_children = _dataAccess.GetChildren(this);
}
return _children;
}
}
And the exception is occurring in the .ToArray() call. I am getting the
// Exceptions:
// System.ArgumentNullException:
// source is null.
(from metadata)
One difference is that in the second form you’re only evaluating the expression
clickedItem.Childrenonce.Imagine if the
Childrenproperty were implemented as:(Or it could just be a race condition, of course.)