When are C# “using” statements most useful?

后端 未结 14 1978
没有蜡笔的小新
没有蜡笔的小新 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 05:53

    Here's what using really does (based on your example)

    Font font1 = new Font(...);
    try
    {
        // code that uses font...
    }
    finally
    {
        if (font1 != null)
            font1.Dispose();
    }
    

    So you don't need to worry about exception making your variable not disposed.

提交回复
热议问题