You still have to dispose of when you're done.
For example, you can call it like this:
using (Pen p = CreatePenFromColor(color)) {
If the method returns an IDisposable, your responsibility is to dispose of it.
[Edit] Now I have a question: are you using the Pen constructor (Brush b).
but. In this case, it seems that Pen doesn't need a Brush instance after the constructor, so your method might look like this:
public Pen CreatePenFromColor(Color c) { using (Brush b = new SolidBrush(c)) { return new Pen(b); } }
b. Why not just use a Pen (color) ?
public Pen CreatePenFromColor(Color c) { return new Pen(c); }
from. (relative to the comment) If the pen contains a link to the brush inside, then you cannot destroy it before you finish using Pen. In this case, I would go to a class that would do the job for me:
public class PenHelper : IDisposable { private readonly Brush _brush; public PenHelper(Color color) { _brush = new SolidBrush(color); } public Pen CreatePen() { return new Pen(_brush); } public void Dispose() { _brush.Dispose(); } }
and then use it like this:
using (PenHelper penHelper = new PenHelper(Color.Black)) { using (Pen pen = penHelper.CreatePen()) {
Disclaimer: IDisposable is not implemented as recommended, but rather for demonstration purposes only. In addition, the entire example is used only to show how to encapsulate the link when necessary. Of course you have to go for Pen (color).