In PHP, C# and may be other languages, why aren’t languages developed to reduce writing code that isn’t really necessary?
Why for example foreach perform a loop on null array or list?
I’m not a professional programmer, but I think this a common sense.
Thank you.
2
Answers
c#
Because foreach is not an assembly level instruction
The
foreach
keyword is "syntactical sugar" from the language, not something that really ends up in the generated code. The codeis actually translated to
In this piece of code, it would be quite ugly to check
myList
for null, as it would require the introduction of a nested if. AndmyList
doesn’t need to be a simple variable, it can be any type of expression or even a method call. It wouldn’t be impossible, but would complicate things for the compiler considerably and add extra code even for cases where it wouldn’t be required.In general, it is also a good idea to let the program crash in case of an error, because it allows detection of errors early. The .NET runtime generally exhibits the concept of throwing early instead of attempting to conceal an error as long as possible. Whether that is "better" is a philosophical question and there are other languages going other paths here, but for C#, that behavior is used consistently throughout.
While rare, the list can technically be a value type, where a null test would be wrong, requiring the compiler to make a type test.
c#
If it really irritates you, perhaps you could work around this using an extension method. Because it’s an extension method, you can call it even on a
null
array or list.You can use this method like so:
Of course you could write this without the extension method too:
This won’t throw an exception because the extension method (null coalescing operator in the second example) prevents the enumerable evaluated by
foreach
from beingnull
.Try it online