C
C#9mo 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
SinFluxx9mo ago
When you create an Instance of an object, that takes up memory/resources
Jimmacle
Jimmacle9mo ago
(unmanaged resources specifically, in this case a file handle)
SinFluxx
SinFluxx9mo 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
Livid9mo ago
so it's like a variable only usable within this section?
SinFluxx
SinFluxx9mo ago
Using the using statement makes sure that instance of the object is automatically disposed when it's out of scope
Jimmacle
Jimmacle9mo 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
Livid9mo ago
oh so it has nothing to do with references (using System;)
Jimmacle
Jimmacle9mo ago
right, different meaning of the keyword here
Livid
Livid9mo ago
email
Jimmacle
Jimmacle9mo 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
Livid9mo 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
Jimmacle9mo ago
no, only what's in the parentheses
Livid
Livid9mo ago
hmm i don't want to be that guy but it seems like bad syntax 😭
Jimmacle
Jimmacle9mo ago
a more recent syntax is a using declaration, which does the same thing but without needing to create a new scope
Livid
Livid9mo ago
oh how?
Jimmacle
Jimmacle9mo ago
for example, using var stream = new FileStream("Document"); in which case the object gets disposed at the end of the method
Livid
Livid9mo ago
that seems like better syntax why 'using' tho why not like Trash Integer myNumber :)
Jimmacle
Jimmacle9mo ago
if i had to guess, to avoid reserving another keyword
Pobiega
Pobiega9mo 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
Jimmacle9mo 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
More Posts