What does use mean (obj = new Object ())?

What does this statement mean in C #?

using (object obj = new object()) { //random stuff } 
+7
c # using-statement
source share
5 answers

This means that obj implements IDisposible and will be correctly deleted after the using block. It is functionally the same as:

 { //Assumes SomeObject implements IDisposable SomeObject obj = new SomeObject(); try { // Do more stuff here. } finally { if (obj != null) { ((IDisposable)obj).Dispose(); } } } 
+13
source share
 using (object obj = new object()) { //random stuff } 

It is equivalent to:

 object obj = new object(); try { // random stuff } finally { ((IDisposable)obj).Dispose(); } 
+5
source share

why does it exist?

It exists for classes in which you care about your life, in particular, when a class wraps a resource in the OS and you want to release it immediately. Otherwise, you have to wait for the CLR (non-deterministic) finalizers.

Examples, file descriptors, database connections, socket connections, ....

+1
source share

this is a way to span an object, so the dispose method is called on exit. This is very useful for database connections in particular. a compilation error will occur if the object does not implement idisposable

0
source share

using ensures that the selected object is highlighted after the use block, even if an unhandled exception occurs in the block.

0
source share

All Articles