Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

c# - IEnumerable<T> null coalescing Extension

I frequently face the problem to check whether an IEnumerable<T> is null before iterating over it through foreach or LINQ queries, then I often come into codes like this:

var myProjection = (myList ?? Enumerable.Empty<T>()).Select(x => x.Foo)...

Hence, I thought to add this extension-method to an Extensions class:

public static class MyExtensions 
{
    public static IEnumerable<T> AsEmptyIfNull<T>(this IEnumerable<T> source)
    {
        return source ?? Enumerable.Empty<T>();
    }
}

A little issue comes immediately in my mind looking at this code, i.e., given the "instance-methods aspect" of extension-methods, it should be implemented as a mere static method, otherwise something like this would be perfectly legal:

IEnumerable<int> list = null;
list.AsEmptyIfNull();

Do you see any other drawback in using it ?
Can such extension leading to some kind of bad-trend in the developer(s), if massively used?


Bonus question:

Can you suggest a better name to it ? :)
(English is not my first language, then I'm not so good in naming...)

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Methods that return an IEnumerable<T> should return an empty one, instead of null. So you wouldn't need this.

See this question : Is it better to return null or empty collection?

Otherwise, your code seems ok.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...