In the example below, will the returned pen be destroyed(disposed) or not?
' VB'
Public Function GetPen() As System.Drawing.Pen
Using pen As New System.Drawing.Pen(_Color, _Width)
pen.DashStyle = _DashStyle
Return pen
End Using
End Function
// C#
public System.Drawing.Pen GetPen()
{
using (System.Drawing.Pen pen = new System.Drawing.Pen(_Color, _Width))
{
pen.DashStyle = _DashStyle;
return pen;
}
}
[EDIT]
Just one more precision… Is the Pen object sent to the caller of GetPen by reference or ‘cloned’ like a structure? I know, this is a class, but with GDI objects I am never sure…
Will it be destroyed(disposed) the pen created in GetPen() when the external method will Dispose its pen obtained with GetPen()?
Yes, pen will be disposed. It’s really a bad idea though; you return a pen that’s already disposed!
What you want to do is to remove the Using statement from GetPen. The Using statement should be used by the GetPen callers:
Or in C#:
[EDIT]
Yes, a reference is returned to the calling method, not a copy. That’s why if you dispose of the pen in GetPen, you can’t use that pen in the calling method 😉
Because of the fact that GetPen and the calling method point to the same Pen object, you just need to call Dispose in the calling method.