public struct S : IDisposable { private bool dispose; public void Dispose() { dispose = true; } public bool GetDispose() { return dispose; } } 

In the example below you will see: false false

 var s = new S(); using (s) { Console.WriteLine(s.GetDispose()); } Console.WriteLine(s.GetDispose()); 

Why did the second time false , because Dispose() called? Thank.

  • why did you decide that he volunteered? - qpeela
  • It was called (add Console.WriteLine to Dispose - the text will be output). - Zufir
  • I started @qpeela in debugging, I volunteered, dispose was dispose to true - Ivan Ivanov
  • Structures can be arbitrarily copied, so IDisposable for a structure is a bad idea. Why not use the class? - VladD
  • @VladD saw this question on one site , it became interesting - Ivan Ivanov

1 answer 1

There is a good article on this topic from Lippert.

Specifically, the answer to your question will be: code

 using (s) { ... } 

will actually be executed as

 using (S s2=s) { ... } 

And since the structures are copied by value, not by reference, all actions will be performed on the copy, not on the original instance. And Dispose will be applied to the copy.

  • And if you create right in using - will help? - Monk
  • this way you can only access inside using . So it won't help - you can't just turn around - Zufir