What gets when the using keyword is used

Here is an example:

using (var someObject = new SomeObject())
{
    var someOtherObject = new SomeOtherObject();
    someOtherObject.someMethod(); 
}

SomeOtherObjectalso implements IDisposable. Will SomeOtherObject also be deleted when SomeObject is deleted? What will happen to SomeOtherObject? (SomeOtherObject is not implemented in the Dispose method for SomeObject)

+3
source share
8 answers

No. Only fields in the use clause will be deleted. In your case, only someObject.

Basically, the code is converted to

var someObject = null;
try
{
  someObject = new SomeObject()

  var someOtherObject = new SomeOtherObject();
  someOtherObject.someMethod(); 
}
finally
{
  if (someObject != null )
  someObject.Dispose()
}
+11
source

No, SomeOtherObjectit will not be selected.

Your code is restructured by the compiler as follows:

var someObject = new SomeObject();
try
{
    var someOtherObject = new SomeOtherObject();
    someOtherObject.someMethod(); 
}
finally
{
    if (someObject != null)
        someObject.Dispose();
}
+5
source

someOtherObject .

:

var someObject = new SomeObject();
try
{
   var someOtherObject = new SomeOtherObject();
   someOtherObject.someMethod(); 
}
finally
{
    ((IDisposable)someObject).Dispose();
}

, .

+5

MSDN :

, IDisposable, using. using Dispose ( , ), , , Dispose. .

, , using. , .

+1

someOtherObject . (), Dispose(), . someObject.Dispose() , using.

+1

:

using (var someObject = new SomeObject()) {
    using (var someOtherObject = new SomeOtherObject()) {
        someOtherObject.someMethod(); 
    }
}

- , , . .

+1

Dispose, someObject, , using. SuppressFinalize Dispose, finalizer ( ).
, someOtherObject, GC , , , - .

0

, ; someOtherObject using; - .

using (Stream stream = File.OpenRead(@"c:\test.txt"))
{
   var v1 = "Hello"; //object declared here, wont be accessible outside the block
   stream.Write(ASCIIEncoding.ASCII.GetBytes("This is a test"), 0, 1024);
} //end of scope of stream object; as well as end of scope of v1 object.

v1 = "World!"; //Error, the object is out of scope!

: " v1 ".

.

    {
        int x=10;
    }

    x = 20; //Compiler error: "The name x does not exist in the current context."

See this and this for more help.

0
source

Source: https://habr.com/ru/post/1735572/


All Articles