2

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.

  1. Why does it return false when clearly there x in the list?
  2. How would I loop through a Guid? List to check if a null Guid? or Guid? with value is in the list?
CharlesB
  • 86,532
  • 28
  • 194
  • 218
Landin Martens
  • 3,283
  • 12
  • 43
  • 61

2 Answers2

3

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 Guids 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);
Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
1

Seems you forgot () near new List<Guid?>. So your code works fine and y.Contains(x) returns true. My code for check Guid in List<Guid?>:

Guid guid = Guid.NewGuid();
foreach (var elem in y)
{
    if (elem != null && guid == elem.Value)
    {
        //CODE
    }
}
shadeglare
  • 7,006
  • 7
  • 47
  • 59