2 ms·
Tip 12: "Working with Null Collections" has it slightly wrong: always return empty colletions, not null ones. There are already helpers for that: https://docs.
by SideburnsOfDoom 8y ago
Tip 12: "Working with Null Collections" has it slightly wrong: always return empty colletions, not null ones.
There are already helpers for that: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.empty https://docs.microsoft.com/en-us/dotnet/api/system.linq.enum...
In this example, of "GetSomeCollectionFromSomewhere" returns null rather than an empty collection, it is in error and the situation should be corrected inside that method, not at all of the callers.
Also, why would you do "if (someCollection.Count > 0) foreach(var item in someCollection) { ... }" ?
This is exactly equivalent to "foreach(var item in someCollection) { ... }"
- manigandham 8y agoAgreed that upstream methods should always return a collection and not null. There is some value in skipping the foreach since that calls GetEnumerator() and may allocate, but that's very high-performance scenarios. Using LINQ to convert everything to a list and then using IList<T>.ForEach is definitely not recommended though. MS themselves have said that method was a mistake and that the foreach construct should always be used for iteration.
- mandeepj 8y agoI think you had misread it. Author was commenting on other developers who have written following code - "How often do .NET developers write something like this:". And, was not promoting this approach. var someCollection = GetSomeCollectionFromSomewhere(); if (someCollection != null && someCollection.Count > 0) { foreach(var item in someCollection) { // Do stuff } }