Is this the right usage of using?

Viewed 67

I am not sure how to use using statement correct.

I try like this:

[HttpDelete("{ClubId}", Name = "DeleteOpenings_Club")]
public async Task<IActionResult> DeleteClub_IsOpening([FromRoute] string ClubId)
{
        using (_db_ClubIsOpen)
        {
            var result = _db_ClubIsOpen.ClubIsOpen_TBL.Where(x => x.FK_Club == ClubId);

            foreach (var item in result)
            {
                _db_ClubIsOpen.ClubIsOpen_TBL.Remove(item);
            }

            _db_ClubIsOpen.SaveChanges();

            return Ok();
        }
}
2 Answers

using is tied into lifetime management, which is a complex question.

Usually, the usage of using you're deploying here would be for things that your method owns; for example, here:

using (var dbContext = new DbContext(whatever))
{
    // some code
}

(or just using var dbContext = new DbContext(whatever); in recent C# versions)

In the above, we are clearly creating the thing, so it is our job to make sure that it gets disposed, which is happening thanks to the using.

However, in the example in the question, it isn't clear what _db_ClubIsOpen is, or what the lifetime is, or who owns it. By default, I would absolutely not assume that a method is responsible for taking ownership of an arbitrary field, so I would not expect to use using here, in the sense of using (_someField) as shown in the question. Instead, I would expect either some DI/IoC framework to deal with that (if it is being injected), or I would expect the type to implement IDipsosable, and deal with disposing the field in Dispose().

From the C# Reference:

Provides a convenient syntax that ensures the correct use of IDisposable objects. Beginning in C# 8.0, the using statement ensures the correct use of IAsyncDisposable objects.

string manyLines=@"This is line one
This is line two
Here is line three
The penultimate line is line four
This is the final, fifth line.";

using (var reader = new StringReader(manyLines))
{
    string? item;
    do {
        item = reader.ReadLine();
        Console.WriteLine(item);
    } while(item != null);
}

The using statement allows you to limit the scope of IDisposable objects and streamline their disposal. Typically you would declare the IDisposable object within the statement of the using structure and use it within the body.

Related