Return Statements inside try Blocks

I recently wrote an extension method named IsNullOrEmpty() for IEnumerable<> types.  Dave had already written one all IEnumerable types:

        public static bool IsNullOrEmpty(this IEnumerable source)

        {

            if (source != null)

            {

                IEnumerator enumerator = source.GetEnumerator();

                return !enumerator.MoveNext();

            }

            return true;

        }

This method has been useful countless times, but Bek realized this could leave open database connections, or cause other problems related to not calling Dispose.  I added the overload:

        public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)

        {

            if (source != null)

            {

                using (IEnumerator<T> enumerator = source.GetEnumerator())

                {

                    return !enumerator.MoveNext();

                }

            }

 

            return true;

        }

A question was raised about whether the generated finally block would be executed if the method returned inside the try block.  I couldn’t remember the answer, but a quick test with LINQPad gave us our answer:

        try

        {

            return;

        }

        finally

        {

            “Hello world”.Dump();

        }

“Hello world” was displayed in the output box.  If the finally block weren’t executed before the method returned, we’d have to store the return value in a temporary variable and place the return statement after the end of the using/finally block.  It’s one of the small tidbits that are nice to know.

Project Euler

The other day my team leader, Mark, pointed me to a great site for testing your problem solving skills.  Project Euler contains over 180 mathematical or computer programming related problems that you can solve yourself.  You can create an account and submit your answers to track your progress.  Once you’ve solved the problem, you gain access that problems thread where you can discuss it.  I’ve started from the beginning using C# in LINQPad.  I do one or two each day as a brain exercise before I begin work.  I’m considering creating a new page to house my solutions, beginning with the nine I’ve solved so far.  In any case, check out the site and try your hand at some of the problems.