nothing collection in for each loop - how to handle it?

vb.net

Solution

Do I need to wrap the foreach loop in a if to check for nothing and only if it is not nothing then enter in the for each loop?

Yes.

If MyStringList IsNot Nothing Then
    For Each item As String In MyStringList 
       'do something ...
    Next
End If

Microsoft says it is by design:

I think that most foreach loops are written with the intent of iterating a non-null collection. If you try iterating through null you should get your exception, so that you can fix your code. Foreach is basically a syntactic convenience. As such, it should not be "magical" and do unexpected things under the hood. I agree with the post that proposed the use of empty collections rather than null. (They can typically be reused quite a bit using singleton techniques).

Problem

How do I handle a for each loop when the collection is nothing, I thought it would just skip over but i get an exeption? Do I need to wrap the foreach loop in a if to check for nothing and only if it is not nothing then enter in the for each loop? ``` For Each item As String In MyStringList 'do something with each item but something myStringList will be nothing? Next ```

Original source