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");
Image may be NSFW.
Clik here to view.
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");
Image may be NSFW.
Clik here to view.
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");
Image may be NSFW.
Clik here to view.
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);
Filed under: Basics Tagged: Basics, C#, foreach, null Image may be NSFW.
Clik here to view.

Clik here to view.
