Solve Memory Leak 101

Recently, I was discussing with a few different people about memory leak.

At first, for languages like C#, Java, etc, they all use managed memory and everything (managed resources) is garbage collected if those managed types are no longer reachable. Normally, it is very safe to assume that managed types are always garbage collectable, including arrays, classes, structures. And, of course, if you open a file, database connection, you need include those in a ‘Using’ block, such as the example below.

// Here 'Using' will dispose command and reader when out of the {} scope.
// And the containing class is garbage collected, but it's resources are explicity deallocated.
// First access the connection string.
// ... This may be autogenerated in Visual Studio.
//
string connectionString =
ConsoleApplication1.Properties.Settings.Default.ConnectionString;
//
// In a using statement, acquire the SqlConnection as a resource.
//
using (SqlConnection con = new SqlConnection(connectionString))
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code uses an SqlCommand based on the SqlConnection.
using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
}
}