Answerwhat does this code print?

time to read 1 min | 128 words

I posted this code previously:

And asked what it prints. This is actually an infinite loop that will print an endless amount of zeros to the console. The question is why.

The answer is that we are running into two separate features of C# that interact with each other in a surprising way.

The issue is that we are using a nullable iterator here, and accessing the struct using the Value property. The problem is that this is a struct, and using a property will cause it to be copied.

So the way it works, the code actually runs:

And now you can more easily see the temporary copies that are created and how because we are using a value type here, we are using a different instance each time.

More posts in "Answer" series:

  1. (22 Jan 2025) What does this code do?
  2. (05 Jan 2023) what does this code print?
  3. (15 Dec 2022) What does this code print?
  4. (07 Apr 2022) Why is this code broken?
  5. (20 Jan 2017) What does this code do?
  6. (16 Aug 2011) Modifying execution approaches
  7. (30 Apr 2011) Stopping the leaks
  8. (24 Dec 2010) This code should never hit production
  9. (21 Dec 2010) Your own ThreadLocal
  10. (11 Feb 2010) Debugging a resource leak
  11. (03 Sep 2009) The lazy loaded inheritance many to one association OR/M conundrum
  12. (04 Sep 2008) Don't stop with the first DSL abstraction
  13. (12 Jun 2008) How many tests?