Search code examples
c#.netdisposeparametersref

Can I dispose multiple Objects in a single go?


I have a class Instance which implements IDisposable interface like shown below.

class Instance : IDisposable
{
    //something
    void Dispose()
    {
        //Disposes something
    }

}

Now in the actual code I have few instances of the Instance which requires to be disposed in the Finally block like below

 finally
        {

            if (inst1 != null)
            {
                inst1.Dispose();
                inst1 = null;
            }

            if (inst2 != null)
            {
                inst2.Dispose();
                inst2 = null;
            }

            if (inst3 != null)
            {
                inst3.Dispose();
                inst3 = null;
            }

        }

So every-time I wanted to Dispose, I have to write the above lines for every single object.

I felt I could use 'params' keyword to reduce the no. LOC (lines of code) like below

   static void DisposeInstance(params Instance[] instances)
    {
        for (int i = 0; i < instances.Length; i++)
        {

            if (instances[i] != null)
            {
                instances[i].Dispose();
                instances[i] = null;
            }
        }
    }

and pass instances in a single shot like,

 DisposeInstance(inst1, inst2, inst3);

But the above function would dispose only the local copy of the Instance and do not exactly dispose the actual objects(instances).

So my question is, if there is any way that I can achieve my goal of disposing objects in a single go and reduce the LOC.

Also can I use 'ref' keyword along with 'params'( which I know gives a compilation error), but somehow mixing these two to get the outcome?

Thanks in Advance!


Solution

  • You don't need to set the objects to null, and with C# 6 you can use the Null-Propagation syntax:

    inst1?.Dispose();
    inst2?.Dispose();
    inst3?.Dispose();
    

    This reduces the noise considerably.