With the following code:
Guid? x = null;
List<Guid?> y = new List<Guid?>();
y.Add(x);
I would expect the following code to return true y.Contains(x); but it returns false.
So this is sort of a two part question.
- Why does it return false when clearly there x in the list?
- How would I loop through a Guid? List to check if a null
Guid?orGuid?with value is in the list?
Let’s examine your code. What it really says without the syntactic sugar is:
Explanation
Nullable<>is actually astruct, so it’s not really evernull; only itsValueproperty has a chance of beingnull, but since its underlying type (Guid) is also astruct, nothing in your list is ever reallynull.So why did I explain that? Well, when it comes time for
List<>.Contains()to do its magic, the conditions of the combination of the twostruct‘sEquals()methods are determining that your emptyGuids don’t equal.Source
How do we fix it?
Since having
Nullablein your solution is pretty useless, I would refactor your code to get rid of it.Guidinstead has a handy-dandyEmptyproperty we can use instead:See the above in action: Ideone
Again, check out this post from Eric Lippert for more information.
Update:
If you’re looking for all
null(or Empty) items in the list, perhaps it would make more sense to check for itemsxin the list wherex.HasValueisfalse: