C
C#14mo ago
Livid

✅ (General Question) Using section

hi why do you use
using(FileStream stream = new FileStream("Document") {
stream.thisIsJustAExample
}
using(FileStream stream = new FileStream("Document") {
stream.thisIsJustAExample
}
what's the point of the Using section / structure?
20 Replies
SinFluxx
SinFluxx14mo ago
When you create an Instance of an object, that takes up memory/resources
Jimmacle
Jimmacle14mo ago
(unmanaged resources specifically, in this case a file handle)
SinFluxx
SinFluxx14mo ago
Some objects are "disposable" i.e. once you're done with them you can call their Dispose method to essentially free up those memory/resources again
Livid
LividOP14mo ago
so it's like a variable only usable within this section?
SinFluxx
SinFluxx14mo ago
Using the using statement makes sure that instance of the object is automatically disposed when it's out of scope
Jimmacle
Jimmacle14mo ago
sorta but that's the case with any scope using is specifically for objects that have unmanaged resources that need to be cleaned up
Livid
LividOP14mo ago
oh so it has nothing to do with references (using System;)
Jimmacle
Jimmacle14mo ago
right, different meaning of the keyword here
Livid
LividOP14mo ago
email
Jimmacle
Jimmacle14mo ago
you're basically saying "when this block of code ends i want you to call Dispose() on the object" that makes sure you aren't leaking unmanaged resources (things that the GC can't clean up itself)
Livid
LividOP14mo ago
does it count for
using(){
var 1_doesThisObjectGetsDisposed?
var 2_doesThisObjectGetsDisposed?
var 3_doesThisObjectGetsDisposed?
}
using(){
var 1_doesThisObjectGetsDisposed?
var 2_doesThisObjectGetsDisposed?
var 3_doesThisObjectGetsDisposed?
}
Jimmacle
Jimmacle14mo ago
no, only what's in the parentheses
Livid
LividOP14mo ago
hmm i don't want to be that guy but it seems like bad syntax 😭
Jimmacle
Jimmacle14mo ago
a more recent syntax is a using declaration, which does the same thing but without needing to create a new scope
Livid
LividOP14mo ago
oh how?
Jimmacle
Jimmacle14mo ago
for example, using var stream = new FileStream("Document"); in which case the object gets disposed at the end of the method
Livid
LividOP14mo ago
that seems like better syntax why 'using' tho why not like Trash Integer myNumber :)
Jimmacle
Jimmacle14mo ago
if i had to guess, to avoid reserving another keyword
Pobiega
Pobiega14mo ago
Using statements have been around for a looooong time The short syntax reusing that keyword makes sense, as to why it was the keyword chosen in the first place.. idk
Jimmacle
Jimmacle14mo ago
probably because it was already reserved for importing namespaces and picking a new keyword would be a breaking change
Want results from more Discord servers?
Add your server