#730 – Check for null Before Iterating Using foreach Statement
December 6, 2012 Leave a comment
The foreach statement allows iterating through all items in a collection.
List<string> dogs = new List<string>(); dogs.Add("Kirby"); dogs.Add("Jack"); foreach (string s in dogs) Console.WriteLine(s); Console.WriteLine("=> Done");
If the collection referenced in the foreach statement is empty, the body of the loop does not execute. No exception is thrown.
List<string> dogs = new List<string>(); foreach (string s in dogs) Console.WriteLine(s); Console.WriteLine("=> Done");
If the object that refers to the collection is null, a NullReferenceException is thrown.
List<string> dogs = null; foreach (string s in dogs) Console.WriteLine(s); Console.WriteLine("=> Done");
Because of this, it’s good practice to check for null before iterating through a collection in a foreach loop.
if (dogs != null) foreach (string s in dogs) Console.WriteLine(s);