skip to Main Content

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


  1. 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 code

    List<string> myList = new List<string>();
    // ... fill list
    foreach(var s in myList)
    {
       // ...
    }
    

    is actually translated to

    IEnumerator it = myList.GetEnumerator();
    
    while (it.MoveNext())
    {
        string s = it.Current;
        // ...
    }
    

    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. And myList 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.

    Login or Signup to reply.
  2. 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.

    
    public static class EnumerableExtensionMethods
    {
        public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
        {
            if (source is null)
            {
                return Enumerable.Empty<T>();
            }
            return source;
        }
    }
    

    You can use this method like so:

    List<string> nullList = null;
    foreach (var entry in nullList.EmptyIfNull())
    {
        // code here
    }
    

    Of course you could write this without the extension method too:

    foreach (var entry in nullList ?? Enumerable.Empty<string>())
    {
        // code here
    }
    

    This won’t throw an exception because the extension method (null coalescing operator in the second example) prevents the enumerable evaluated by foreach from being null.

    Try it online

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search