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

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

    why should we use IDisposable

    Short answer is that any class that doesn't implement IDisposable cannot be used with using.

    when using statement can itself release resources

    no it cannot release resources itself.

    As i wrote above that you need to implement IDisposable inorder to be able to use using. Now, when you implement IDisposable you get a Dispose method. In this method you write all the code that should take care of all the resources that needs to be disposed off when the object is no longer required.

    The purpose of USING is that when an object goes out of its scope, it will call the dispose method and that is it.

    Example

     using(SomeClass c = new SomeClass())
     { }
    

    will translate to

     try
     {
         SomeClass c = new SomeClass();
     }
     finally
     {
         c.Dispose();
     }
    

提交回复
热议问题