Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using statement without curly braces

Tags:

c#

I'm looking at the Npgsql getting started examples and having a hard time understanding the use of the using statement.

var connString = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase";

await using var conn = new NpgsqlConnection(connString);
await conn.OpenAsync();

// Insert some data
await using (var cmd = new NpgsqlCommand("INSERT INTO data (some_field) VALUES (@p)", conn))
{
 cmd.Parameters.AddWithValue("p", "Hello world");
 await cmd.ExecuteNonQueryAsync();
}

Why would one add "using" to the declaration of conn variable?

await using var conn = new NpgslConnection(connString);

Also, as there is no curly braces, why is conn not disposed before it is being used when inserting data in the following line?

await using (var cmd = new NpgsqlCommand("INSERT INTO data (some_field) VALUES (@p)", conn))

When will it be disposed?

like image 319
Thomas Avatar asked Apr 12 '26 08:04

Thomas


1 Answers

using adding for guarantee what your connection will be close after transaction

await using var conn = new NpgslConnection(connString);

On your last question.

With the new C# 8 using declaration, the code with the using statement can be simplified. Curly brackets are no longer needed. At the end of the scope of the variable r (which is here the end of the method), the Dispose method is invoked. Here, the compiler also creates a *try/finally block to make sure Dispose is called if errors occur.

like image 156
evilGenius Avatar answered Apr 14 '26 21:04

evilGenius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!