Search code examples
c#fontsdisposeencapsulation

C# - Design-related dispose question (take two)


I asked a question earlier today, but I think I need to approach it in a different way (on top of that there was a "hang up" in regards to DataSet).

Here's a class that encapsulates the creation of a Font (in other words, it is reading data from an xml file and is creating a font, at runtime, based on what it reads from that file):

public class FontCreator
{
    private Font m_TheFont = null;

    public FontCreator( ... some parameters ... )
    {
        m_TheFont = GetTheFont();
    }

    public Font TheFont
    {
        return m_TheFont;
    }

    private Font GetTheFont()
    {
        // code, and more code, that eventually leads to:

        Font f = new Font(fntFamily, fntSize, fntStyle);
        return f;
    }
}

The consumer of the FontCreator class looks something like:

public class TheConsumer()
{
    private FontCreator m_FontCreator = null;

    public TheConsumer()
    {
        m_FontCreator = new m_FontCreator( ... some parameters ... );
        Initialize();
    }

    private void Initialize()
    {
        InitializeThis();
        InitializeThat();
    }

    private void InitializeThis()
    {
        .... some code ...
        SomeObject.ApplyFont(m_FontCreator.TheFont);
    }

    private void InitializeThat()
    {
        ... some code ...
        SomeObject.ApplyFont(m_FontCreator.TheFont);
    }
}

What code do you add, and where, to ensure that "TheFont"'s Dispose method is explicitly called?


Solution

  • If you don't wish to maintain a reference to TheFont after it is initially used, then call it's Dispose method in your constructor, right after Initialize. If you wish to keep TheConsumer alive for a while and maintain a reference to TheFont, it gets more interesting. Two Options:

    1. You can have TheFont's dispose method called from the Destructor of the TheConsumer object. This is not the common practice and has problems. Mainly, this is not called until garbage collection happens. Better is:
    2. You can make the TheConsumer object itself implement IDisposable, and call TheFont.Dispose from TheConsumer.Dispose. Since TheConsumer implements IDisposable, the code that uses it should call its Dispose method.

    Edit in response to harsh comment! Yes, I should have made clear to only use 1 in addition to 2, if at all. I know all developers everywhere are supposed to notice when IDisposable is implemented, but they often don't. If the referenced managed resource might really remain around a long time and cause problems if not properly disposed, I sometimes have a safety Dispose() method call in the destructor of the object holding the reference. Is that so wrong? :)