If yield return never occurs, is null returned?

2019-01-27 13:50发布

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?

3条回答
Luminary・发光体
2楼-- · 2019-01-27 14:22

Indeed, 2.0 coders who leant toward heavy use of enumerations would have a standard piece in their toolkits of:

public static IEnumerable<T> EmptyEnum<T>()
{
    yield break;
}

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

查看更多
男人必须洒脱
3楼-- · 2019-01-27 14:30

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.

查看更多
干净又极端
4楼-- · 2019-01-27 14:35

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 to Enumerable.Empty<T>.

查看更多
登录 后发表回答