Computer Science

using declaration


• Here you create an object called context.
• It remains in memory until you close it (context.Dispose() or context.Close()).
• If you don't dispose of it manually, the garbage collector will clean it up after a while, but not immediately.
• In this case, connections can remain open (e.g. database connection pool, transaction, etc.).

                        var context = new DbContext();
                    

Example


• This is the "using declaration" feature introduced in C# 8.
• It is automatically disposed when the context scope (of the method or curly braces) is exhausted.
• So you don't need to call Dispose().

                        using var context = new DbContext();
                    

Result


• var context = You must dispose of the object.
• When using var context = Scope is finished, it is automatically disposed, resource management is safer.