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.

Advertisements

One thought on “Return Statements inside try Blocks

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s