2

Does an ienumerable obtained from a yield expression can ever be null?

svick
  • 236,525
  • 50
  • 385
  • 514
Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116

1 Answers1

12

No. The C# compiler converts your iterator block into an iterator instance, which is what is returned from your method. This can never be null.

That said, it is of course possible to yield null values within your enumeration, provided that the generic type of your enumerable is a reference type or a nullable type.

Douglas
  • 53,759
  • 13
  • 140
  • 188
  • What do you mean by "your iterator block"? You can get null values back, AND you can make `GetEnumerator()` return null, so I'm not sure what it is you're saying can't be null. – Matthew Watson Jul 06 '13 at 15:16
  • 2
    @MatthewWatson: A method body that contains a `yield return` or `yield break` statement is called an *iterator block* in the C# specification. – Eric Lippert Jul 06 '13 at 15:18
  • Ah ok I see what he means now. Still not sure if that's what the OP meant... probably it was though. – Matthew Watson Jul 06 '13 at 15:19