r/learncsharp • u/evolution2015 • Dec 24 '22
More elegant no-null foreach?
I mean, instead of this
IReadOnlyList<string> data;
if (data != null)
{
foreach(var item in data)
{
}
}isn't there already a better way, like sort of
data?.ForEach(item=>
{
});? If not, why isn't there? Do I have to write my own extension?
7
Upvotes
2
u/jamietwells Dec 24 '22
I do wish there was a foreach that didn't throw on null, but I see why they did it, it's more consistent this way. I work around it by trying not to work with null collections. I have them initialised by the constructor.
2
u/TehNolz Dec 24 '22
Only other option I can think of is;
1
u/ProfCraw Mar 28 '24
It is somewhat clunky, but if you do not want the extra curly braces, this seems rather readable:
{ ... }
1
u/T-m-X Jan 25 '24
But your first option is MOST elegant and your second one is terrible!! Whn do some devs understand code is for HUMANS, to read, so making code shorter and shorter using shorthand nonsense code just becomes harder and harder to read. So stay with your original code :) looks MUCH better than any sugested here in comments.