Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# using: constructor in a different method

Tags:

c#

using

All online examples I can find for C#'s using instantiate directly within the using parentheses:

using (var cnx = new SqlConnection()) { }

I would think that the following should act identically, but I still seem to have locked resources:

SqlConnection GetConnection() { return new SqlConnection(); }
void foo()
{
    using (var cnx = GetConnection()) { }
}

When I step through my program and get to the line following the using's closing brace, I'd expect to be able to alter the db any way I want using SQL Server Management Studio, but I can't. When I close my app, the errors go away.

This isn't segregated to SQL; I've also experienced this with opening file steams in this way. That is: step past the using block but the OS won't allow an external app to alter the file.

Am I violating some part of the using contract?

like image 875
Dinah Avatar asked Feb 13 '13 16:02

Dinah


2 Answers

It's absolutely fine to use a method which returns the appropriate resource. In particular, this is pretty common:

using (var writer = File.CreateText(path))
{
}

(and similar methods in File).

Basically, this isn't to do with calling a method or calling a constructor - there must be something else wrong. If you can create a short but complete program demonstrating the problem (ideally with files instead of a database) then we're likely to be able to help you find out what is the problem, not just what isn't :)

like image 167
Jon Skeet Avatar answered Sep 20 '22 13:09

Jon Skeet


If you have connection pooling enabled, 'Dispose' wont necessarily physically close the connection.

like image 21
Matt Randle Avatar answered Sep 20 '22 13:09

Matt Randle