IEnumerable null coalescing Extension?

Methods that return an IEnumerable 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.

Methods that return an IEnumerable 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.

1 Yes, that's true, but not always you can change the code to get this result (e.g. When using API). To give a real example, try to serialize an empty list with protobuf, then deserialize it: you will get null :) – digEmAll Apr 12 at 19:21.

It's generally a bad idea to return a null instead of an empty sequence if you can control it. This is self-explanatory if you consider that when someone is asked to produce a collection, returning null is not like saying "the collection is empty" but "there is no such collection at all". If you own the methods returning the enumerables, then returning an empty IEnumerable (which can even be a special purpose readonly static object if it might be returned a lot) is the way to go, period.

If you are forced to use a bad-mannered library that has the habit of returning null in such cases, then this an extension method might be a solution, but again I wouldn't prefer it. It's probably better to wrap the bad-mannered methods in your own versions that do the coalescing where people won't see it. This way you get both the convenience of always having an enumerable instead of null and the correctness of not supporting the "return null" paradigm.

Yes, probably the best thing to do is to wrap bad-mannered libraries. Anyway, create this kind of extension doesn't seem so harmful, does it? – digEmAll Apr 12 at 19:43 @digEmAll: The harm is only that people who see it might think that it's OK for methods to return null instead of empty collections and write their own such methods, which would perpetuate the problem.

Other than that, I don't see any harm. – Jon Apr 12 at 19:44 yes you're right. Thanks :) – digEmAll Apr 12 at 19:46.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions