Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I have a return within the code of Using(connection) does the connection and db objects gets dismissed properly

Tags:

c#

sql

asp.net

I'm not sure if my question is clear so here's a code sample:

    public static bool isRecordExist(int ID)
    {
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            using (SqlCommand command = new SqlCommand(commandText, connection))
            {
                int flag = int.Parse(command.ExecuteScalar);

                if (flag)
                    return false;
                else
                    return true;
            }
        }
    }

So, now I understand that I don't need to close or dismiss any Sql objects when I have the 'using' keyword, because it does that automatically as soon as you get our of it's brackets but now the we reach to the 'return' part. will it dismiss and close the objects properly or do I need to save this value and make my check and 'return' outside the 'using' code ?

like image 693
Mazen Elkashef Avatar asked Jan 16 '26 22:01

Mazen Elkashef


1 Answers

Yes it closes automatically. Exiting a using block calls .Dispose() on the object in question which for a SqlConnection will close the connection and any open resources.

Does End Using close an open SQL Connection

like image 53
Carter Medlin Avatar answered Jan 19 '26 17:01

Carter Medlin



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!