The method returns IEnumerable via a yield return statement.
If the yield statement never occurs (it's inside conditional logic), will the method return null, or will it return an Enumerable with a count of 0?
The method returns IEnumerable via a yield return statement.
If the yield statement never occurs (it's inside conditional logic), will the method return null, or will it return an Enumerable with a count of 0?
Indeed, 2.0 coders who leant toward heavy use of enumerations would have a standard piece in their toolkits of:
Before System.Linq.Enumerable.Empty() came along . Very useful in a lot of cases, quite often precisely because it doesn't return null. For example, if GetIntEnum() can return some sort of IEnumerable type but can also return null, then
GetIntEnum() ?? Enumerable.Empty<T>()
gives us something that is always safe to enumerate over (assuming that's the desired behviour in the case of null results).A valid IEnumerable that produces no values when you iterate through it.
Just think of it: You can store the IEnumerable generator in a variable - the code itself just gets executed when you actually iterate through the results. How could you execute the code if you had
null
? Or how did you know the function doesn't yield anything without running it.The latter -- you're going to be able to
GetEnumerator()
no matter what, there just won't be any items to enumerate. This is equivalent toEnumerable.Empty<T>
.