When are C# “using” statements most useful?

后端 未结 14 2204
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 05:33

So a using statement automatically calls the dispose method on the object that is being \"used\", when the using block is exited, right?

But when is this necessary/benef

14条回答
  •  孤街浪徒
    2021-02-13 06:01

    Dispose is called when it exits the using statement because it's explicitly called by that construct. The dispose method isn't called explicitly when the variable goes out of scope (exiting method).

    The behavior you MAY observe that looks like that is that usually things that implement IDisposable also call the Dispose method in the classes destructor, and the destructor COULD be called soon after the variable goes out of scope, but not guaranteed. The destructor is invoked by the garbage collector.

提交回复
热议问题