2

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();
        }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JdDEV
  • 43
  • 5
  • no is my DBContext i work with EF6 – JdDEV Apr 22 '21 at 14:34
  • 2
    What is `_db_ClubIsOpen`? where did it come from? what is the expected lifetime? I would *not* assume that your controller method is meant to be disposing something that *it didn't create*, so... who did create it? lifetime management is complex, and we don't have all the context here – Marc Gravell Apr 22 '21 at 14:34
  • Then you probably don't want `using` - it's just syntactic sugar, `using(X){ ... }` is translated to `X; try { ... } finally {X.Dispose()}` – Mathias R. Jessen Apr 22 '21 at 14:35
  • `_db_ClubIsOpen` almost sounds like it would be a `bool`, to be honest. – ProgrammingLlama Apr 22 '21 at 14:35
  • I check it and yes is implement IDisposable @Llama – JdDEV Apr 22 '21 at 14:36
  • Thanks @MathiasR.Jessen "syntacitc sugar" is the keyword for me.. – JdDEV Apr 22 '21 at 14:38
  • @MathiasR.Jessen it absolutely is NOT syntactic sugar in C#. To answer OPs question, most likely the answer is No. You wouldn't want to dispose of a member object within a function and your using statement should be where you create the object as well. – Lawrence Johnson Apr 22 '21 at 14:40
  • @LawrenceJohnson Fair, what would be the correct way of describing "gets lowered to the same IL as ..."? – Mathias R. Jessen Apr 22 '21 at 14:42
  • @MathiasR.Jessen you wouldn't say that because it's not correct. There is no `try/catch/finally` block that's created automatically when you use `using`. The using statement helps with garbage collection, for disposable interfaces, but it does not load a try/catch for you. – Lawrence Johnson Apr 22 '21 at 14:44
  • @LawrenceJohnson [SharpLab seems to think there is](https://sharplab.io/#v2:D4AQTAjAsAUCAMACEEB0ARAhgF0wblhAGZkxEBhRAb1kTuRJABZEBZACgEprb6+FE7AG6YATomwBbAA6IAvIgB2AUwDuiLLgAqmAEYAbZV068+dGjDP0AvqcS2Y1oA==). Note that Mathias never said that it created a `catch` block. – ProgrammingLlama Apr 22 '21 at 14:45
  • 2
    @Lawrence `using` *absolutely* generates a `try`/`finally`; this is formally documented in the language specification §13.14 (ECMA 334); additionally, `using` has *no relation whatsoever* directly to GC – Marc Gravell Apr 22 '21 at 14:49
  • I was hung up on the `catch` part, but I see now that wasn't in the original comment - my b. – Lawrence Johnson Apr 22 '21 at 14:50

2 Answers2

5

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().

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

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.

Isaac Corbrey
  • 553
  • 3
  • 20
  • I think everything in here is *true*, but that *at the same time*: it doesn't really help answer whether the code in the question is correct/incorrect – Marc Gravell Apr 22 '21 at 14:43
  • Yeah I realize that now :/ I was hoping it would steer OP in the right direction but your answer fleshed that out much better. Still trying to figure out how best to answer questions on SO – Isaac Corbrey Apr 22 '21 at 14:45