✅ (General Question) Using section
hi why do you use
what's the point of the Using section / structure?
20 Replies
When you create an Instance of an object, that takes up memory/resources
(unmanaged resources specifically, in this case a file handle)
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
so it's like a variable only usable within this section?
Using the using statement makes sure that instance of the object is automatically disposed when it's out of scope
sorta but that's the case with any scope
using
is specifically for objects that have unmanaged resources that need to be cleaned upoh so it has nothing to do with references (
using System;
)right, different meaning of the keyword here
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)
does it count for
no, only what's in the parentheses
hmm i don't want to be that guy but it seems like bad syntax 😭
a more recent syntax is a
using
declaration, which does the same thing but without needing to create a new scopeoh how?
for example,
using var stream = new FileStream("Document");
in which case the object gets disposed at the end of the methodthat seems like better syntax
why 'using' tho
why not like
Trash Integer myNumber
:)if i had to guess, to avoid reserving another keyword
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
probably because it was already reserved for importing namespaces
and picking a new keyword would be a breaking change