Quantcast
Viewing latest article 6
Browse Latest Browse All 8

#730 – Check for null Before Iterating Using foreach Statement

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.
730-001

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.
730-002

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.
730-003

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.
Image may be NSFW.
Clik here to view.

Viewing latest article 6
Browse Latest Browse All 8

Trending Articles