Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of 'using' in .NET

Tags:

.net

using

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()?

like image 981
serhio Avatar asked Jan 13 '10 14:01

serhio


People also ask

Why is using used in C#?

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.

What is a using directive in C#?

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.

Does using dispose C#?

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.

What is using static?

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.


1 Answers

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.

like image 85
David M Avatar answered Nov 15 '22 10:11

David M