Let's examine your code. What it really says without the syntactic sugar is:
Nullable<Guid> x = new Nullable<Guid>(new Guid());
List<Nullable<Guid>> y = new List<Nullable<Guid>>();
y.Add(x);
Explanation
Nullable<>
is actually a struct
, so it's not really ever null
; only its Value
property has a chance of being null
, but since its underlying type (Guid
) is also a struct
, nothing in your list is ever really null
.
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 two struct
's Equals()
methods are determining that your empty Guid
s don't equal.
The nullable equality operator that takes two nullable guids is applicable in this situation, will be called, and will always return false.
Source
How do we fix it?
Since having Nullable
in your solution is pretty useless, I would refactor your code to get rid of it. Guid
instead has a handy-dandy Empty
property we can use instead:
Guid x = Guid.Empty;
List<Guid> y = new List<Guid>();
y.Add(x);
Console.WriteLine(y.Contains(x)); // True
Console.WriteLine(y.Contains(Guid.Empty)); // True
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 items x
in the list where x.HasValue
is false
:
var myList = new List<Guid>();
... /* add to myList */
var theEmpties = myList.Where(x => x == Guid.Empty);