Why should I use IDisposable instead of using in c#?

前端 未结 6 1794
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 07:59

Today, I wanted to perform an operation with a file so I came up with this code

    class Test1
    {
        Test1()
        {
            using (var fileSt         


        
6条回答
  •  一生所求
    2021-01-03 08:07

    A little note first, since you seem a bit confused about how using and IDisposable interact with each other: The reason why you're able to say using (FileStream fileStream = Whatever()) { ... } is precisely because the FileStream class implements IDisposable. What your coworkers have suggested is that you implement IDisposable on your class so that you'll be able to say using (Test test = new Test()) { ... }.

    For what it's worth, I think the way you wrote the code initially is strongly preferable to the suggested change, unless there's some compelling reason why you might want to keep the FileStream open for the entire lifetime of a Test1 instance. One reason why this might be the case is that the file might be subject to change from some other source after the constructor of Test1 has been called, in which case you'll be stuck with an older copy of the data. Another reason for keeping the FileStream open could be if you specifically want to lock the file from being written to from elsewhere while a Test1 object is alive.

    In general, it's good practice to release resources as soon as possible, which your original code seems to do. One thing I'm a little skeptical of is that the work is done in your constructor instead of in some method that's explicitly called from the outside (explanation: http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/). But this is a different matter altogether, and independent of the question of whether to make your class implement IDisposable.

提交回复
热议问题