简体   繁体   中英

C#: Setting child class to null on parents dispose?

Is my implementation of dispose correct? In this question I'm sort of asking 1 question but about 1 topic to understand it better.

  • Do I need to set lists, dictionarys and any type of collection to null on dispose?
  • Do I need to clear collections on dispose?
  • Do I need to set child class to null on dispose?

Take this code for example..

public class ParentClass : IDisposable
{
    private readonly ChildClass;

    public ParentClass()
    {
        ChildClass = new ParentClass();
    }

    public void Dispose()
    {
        ChildClass.Dispose();
        ChildClass = null;
    }
}

public class ChildClass : IDisposable
{
    private Dictionary<int> myIds;

    public ChildClass()
    {
        myIds = new Dictionary<int>();
    }

    public void Dispose()
    {
        myIds.Clear();
        myIds = null;
    }
}

The answer to all your questions is no . .NET programs use managed code, which means the platform will clean up all these objects for you.

Now, if you access an unmanaged resource such as a file, database, etc. That's when you need to use IDisposable to ensure that any unmanaged resources get cleaned up in a timely manner.

But things like Dictionary<> will clean up themselves.

Whether members should be set to null in Dispose() can be answered in different ways. It's (as said in many other answers - see "Related" on the right) only necessary for members that are on itself disposable.

First, it's obviously only possible to set a member to null in Dispose() if it is not declared as readonly. Making them not readonly just because of this is probably not a good design pattern. If you do set it to null after dispose, you also have to check for null before doing so, because you must always be able to call Dispose() multiple times without side effects or exceptions. Setting a member to null also helps in preventing that you accidentally use the object again after dispose (because accessing the member will cause an exception).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM