#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");

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");

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");

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);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: