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.
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