✅ using
I keep seeing variables defined within a using, like
what is using? why do people use it? what are the risks of not using it?
I think this just disposes of the connection variable (for sure) after its done, but i see it used mostly when dealing with databases. is there a reason for this. If my variables are within a method they get disposed at the end of the method right? How concerned should i be about this?
7 Replies
If my variables are within a method they get disposed at the end of the method right?No @hutonahill C# does not have RAII.
not sure what that is, but very very good to know.
and very annoying
is there a reason it doesent dispose at the end of the method?
I'm actually not sure if it's due to problems with escape analysis (that is, whether the compiler knows the value has "escaped" the method) or just a delibrate choice.
#roslyn would be a good place to ask that question.
that being said, nowadays there's a more compact syntax, no need for indenting
$using
huh, no tag? alright
in the former, the using'd var is disposed at the end of the enclosing block
nifty. and that just disposes of connection?
well,
using
is for anything that implements IDisposable
, the semantics of which varies by types
for file streams for example, it closes the stream
for SQLiteConnection, closes the connection
etc.using statement - ensure the correct use of disposable objects - C#...
Use the C# using statement or declaration to ensure the correct use of disposable objects
great. that answers my questions. thanks