Multiple choice technology programming languages

You develop a Windows-based application ABCApp by using Visual Studio .NET. ABCApp uses a SqlConnection object for database access. You typically run ABCApp on a computer that has limited RAM and hard disk space. After the code finishes using the SqlConnection object, you must ensure that the connection is closed and that any resources consumed by the object are released immediately. What should you do?

  1. Call the Finalize method of the SqlConnection object.

  2. Call the Dispose method of the SqlConnection object.

  3. Set the SqlConnection object equal to Nothing.

  4. Set the SqlConnection object equal to “”.

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

The Dispose method is the correct approach to immediately release resources and close the connection. Dispose is deterministic - it frees resources right when called. Finalize is non-deterministic (called by garbage collector eventually), setting to Nothing just removes the reference without closing the connection, and setting to "" is invalid for objects.

AI explanation

In .NET, deterministic cleanup of unmanaged/scarce resources (like an open database connection) is done by explicitly calling Dispose() on the object (SqlConnection implements IDisposable), which immediately releases the connection and its resources. Relying on Finalize (the GC finalizer) doesn't guarantee immediate release — it runs at an indeterminate future time during garbage collection. Setting the reference to Nothing or an empty string just removes your variable's reference; it doesn't tell the runtime to release the underlying connection resources right away.