C
C#4mo ago
hutoanhill

✅ using

I keep seeing variables defined within a using, like
using(var connection = new SQLiteConnection()){
...
using(var connection = new SQLiteConnection()){
...
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
jcotton42
jcotton424mo ago
If my variables are within a method they get disposed at the end of the method right?
No @hutonahill C# does not have RAII.
hutoanhill
hutoanhillOP4mo ago
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?
jcotton42
jcotton424mo ago
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
using var connection = new SQLiteConnection();
// code here

// instead of
using (var connection = new SQLiteConnection())
{
// code here
}
using var connection = new SQLiteConnection();
// code here

// instead of
using (var connection = new SQLiteConnection())
{
// code here
}
in the former, the using'd var is disposed at the end of the enclosing block
hutoanhill
hutoanhillOP4mo ago
nifty. and that just disposes of connection?
jcotton42
jcotton424mo ago
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.
hutoanhill
hutoanhillOP4mo ago
great. that answers my questions. thanks
Want results from more Discord servers?
Add your server