Search code examples
c#visual-studiousingc#-8.0

Visual Studio Recommending to Simplify Using Command


I've noticed since updating Visual Studio that it is now recommending to simplify my MySQL using statements.

It wants to change this:

            using (MySqlCommand command = new MySqlCommand(sql_string, connection))
            {
                command.Parameters.AddWithValue("@id", id);

                MySqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    reader.Read();

                    business = new Business()
                    {
                        Id = int.Parse(reader["id"].ToString()),
                        Name = reader["name"].ToString(),
                    };

                    reader.Dispose();
                }
            }

Into this:

            using MySqlCommand command = new MySqlCommand(sql_string, connection);
            command.Parameters.AddWithValue("@id", id);

            MySqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Read();

                business = new Business()
                {
                    Id = int.Parse(reader["id"].ToString()),
                    Name = reader["name"].ToString(),
                };

                reader.Dispose();
            }

My question is, previously the code would be wrapped in brackets like so:

            using (MySqlCommand command = new MySqlCommand(sql_string, connection))
            {

            }

Is the recommended suggestion by IntelliSense valid and won't cause any leaks?


Solution

  • This is called a Using Declaration.

    A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

    As long as you need the using variable in the same scope suggested by the compiler, it should not be a problem.

    Reference: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations