I appreciate that this is a rather broad question, so I'm going to specify details to try to explain why I am struggling to understand the process.
As far as I am aware, VB.Net and the .NET framework generally, has inbuilt Garbage Collection, which means when I Dim
a variable and assign a value to it, I don't need to declare it null, or "dispose" of it after.
Recently, in another question, I was reminded about disposing my Pen
and Brush
objects in this code example:
Private Sub pbProfilePicture_Paint(sender As Object, e As PaintEventArgs) Handles pbProfilePicture.Paint
Dim myPen As Pen
Dim myBrush As Brush
myPen = New Pen(Drawing.Color.FromArgb(180, 204, 112), 1)
myBrush = New SolidBrush(Color.FromArgb(180, 204, 112))
Dim myGraphics As Graphics = e.Graphics
myGraphics.DrawEllipse(myPen, 28, 28, 12, 12)
myGraphics.FillEllipse(myBrush, 28, 28, 12, 12)
End Sub
I was told to use either the Using
command or dispose of them manually (assuming .Dispose()
for each object). My question is, why do I need to dispose of the objects in this case? Is there a rule of thumb for what objects need to be disposed and what is handled automatically? As far as I can tell from documentation, it seems to follow the pattern of disposing anything that is initialised with the New
keyword.
Are the consequences of not disposing objects, clogging up and increasing memory usage in the application?
Any help on where I can get started on this would be really useful.