Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected Guid change during a Linq request

I would like to understand the following snippet:

class TestNewGuid
{
    public Guid RequestId { get; set; } = Guid.NewGuid();

    // any other fields
}

[Fact]
public void Test()
{
    var toInitAnEnumerable = new int[] {1};
    var requests = toInitAnEnumerable
        .Select(a => new TestNewGuid());

    var requestIds = requests
        .Select(a => a.RequestId)
        .ToHashSet(); // this calls the TestNewGuid's constructor
    
    Assert.Equal(requestIds.First(), requests.First().RequestId); // Always fails
}

I’m surprise by the fact that the RequestId changes.

I know that ToHashSet() will create a copy, but because I have the .Select(a => a.RequestId) before, I don’t understand why it creates a copy of TestNewGuid and not of the Guid.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any idea?

>Solution :

Select is not evaluated when you call it, it is what is known as "deferred execution" – which is to say it only runs when a method which will materialize the enumerable is executed. There are 2 such methods in your code; First() in the assertion, and ToHashSet().

Both of these calls will cause your enumerable to be evaluated, and thus call your construction of TestNewGuid

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading