I am planning to use a shared variable to implement a logging facility. Have a look at the code below:
Imports System.IO
Public Class TestClass
Public Shared objError As New StreamWriter("C:\Test.txt")
End Class
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
TestClass.objError.WriteLine("Error 1")
TestClass.objError.WriteLine("Error 2")
TestClass.objError.WriteLine("Error 3")
'TestClass.objError.Close()
TestClass.objError.WriteLine("Error 4")
TestClass.objError = Nothing
Catch ex As Exception
End Try
End Sub
I don't understand how this shared variable is created and destroyed (I assume it is created before the form_load and destroyed by the form_unload). I also don't understand why it is possible to set the reference to the static variable to Nothing; surely the variable should exist until the program ends? (Q1, part 1) I realise this is a simple question.
Is there a better way to implement a logging mechanism? (Q1 part 2). The logging mechanism writes errors and log entries.
UPDATE I think I have found my answer here: http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx. "A static variable continues to exist and retains its most recent value. The next time your code calls the procedure, the variable is not reinitialized, and it still holds the latest value that you assigned to it. A static variable continues to exist for the lifetime of the class or module that it is defined in."
I am not convinced that this is the best way to create a logging facility. Therefore part 2 to my question is still open.