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

前端 未结 6 1818
没有蜡笔的小新
没有蜡笔的小新 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:08

    The answer given by "No One" is correct that using block can only be used for the classes that implement the IDisposable interface and explanation for it is perfect. The question from your side is "Why I need to add IDisposable on Test class and But on code review, I was asked to implement IDisposable interface and Finalizer methods on Test class."
    The answer is simple
    1) As the per the coding standards followed by so many developers it is always good to implement IDisposable on the classes which use some resources and once the scope of that object is over the Dispose method in that class will make sure all the resources have been released.
    2) The class that has been written is never such that in future no changes will be made and if such changes are made and new resources are added then the developer knows that he has to release those resources in Dispose function.

提交回复
热议问题