C
C#2y ago
Elio

Using instruction

Hi, i would like to know when we are using the instruction "using like this :
using (var context = new BloggingContext())
{
var blogs = context.Blogs.ToList();
}
using (var context = new BloggingContext())
{
var blogs = context.Blogs.ToList();
}
does it automatically dispose all the variable inside "blogs" and "context" ?
5 Replies
Thinker
Thinker2y ago
It automatically disposes context when execution reaches the closing }. But it won't dispose anything else
Chiyoko_S
Chiyoko_S2y ago
yeah, blogs simply goes out of scope and that's it, only context gets disposed of could do using var if you need to dispose of blogs as well
MODiX
MODiX2y ago
thinker227#5176
REPL Result: Success
class C : IDisposable {
public void Dispose() => Console.WriteLine("dispose");
}

using (var c = new C()) {
Console.WriteLine("in scope");
}
class C : IDisposable {
public void Dispose() => Console.WriteLine("dispose");
}

using (var c = new C()) {
Console.WriteLine("in scope");
}
Console Output
in scope
dispose
in scope
dispose
Compile: 621.252ms | Execution: 49.092ms | React with ❌ to remove this embed.
Elio
Elio2y ago
Thanks
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View