Search code examples
c#winformsmemorygraphicspath

Should the GraphicsPath be disposed after use


I am making some utility classes that make different types of symbols to place onto an elevation of CAD drawings. I want to make sure that if I need to dispose of the GraphicsPath object that I do so.

In the code below from inside the getCircle function it shows that I am passing the myPath "GraphicsPath" object to the AddStringToPath function.

I cannot use the using(){} scope for this because I am passing the myPath graphics object as a ref.

Is this design ok to use or do I need to go about this a different way to ensure garbage collection?

GraphicsPath getCircle(Graphics dc, string text = "")
{
    GraphicsPath myPath = new GraphicsPath();
    myPath.AddEllipse(symbolCircle);
    AddStringToPath(dc, ref myPath, text);
    return myPath;
}

void AddStringToPath(Graphics dc, ref GraphicsPath path, string text)
{
    SizeF textSize = dc.MeasureString(text, elevFont);
    var centerX = (path.GetBounds().Width / 2) - (textSize.Width / 2);
    var centerY = (path.GetBounds().Height / 2) - (textSize.Height / 2);

    // Add the string to the path.
    path.AddString(text,
        elevFont.FontFamily,
        (int)elevFont.Style,
        elevFont.Size,
        new PointF(centerX + 2, centerY + 2),
        StringFormat.GenericDefault);
}

Solution

  • your function which creates the path should be used later in a using statement

     using(var path = getCircle(dc, "Text"))
     {
          // do something with path
     }
    

    it would also be better, if you would call the function CreateCircle instead of getCircle