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()
?
In C#, the using keyword has two purposes: The first is the using directive, which is used to import namespaces at the top of a code file. The second is the using statement. C# 8 using statements ensure that classes that implement the IDisposable interface call their dispose method.
The using directive allows you to use types defined in a namespace without specifying the fully qualified namespace of that type. In its basic form, the using directive imports all the types from a single namespace, as shown in the following example: C# Copy. using System.
C# provides a special "using" statement to call Dispose method explicitly. using statement gives you a proper way to call the Dispose method on the object. In using statement, we instantiate an object in the statement. At the end of using statement block, it automatically calls the Dispose method.
The using static DirectiveThis directive allows us to reference static members without needing to reference the namespace or even the type itself. using static directives can also be used to reference nested types. The WriteLine method that we've been using in our examples is a static member of the Console class.
Yes, it will be disposed. You are then returning it in a disposed state, so it won't be any good for anything. If you want to use a factory method like this to return a Pen
instance, you'll need to deal with disposing it yourself externally to the method, not using a using
block within the method like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With