Singleton Method in VB .NET

  • Thread starter Thread starter Aaron
  • Start date Start date
A

Aaron

Is the singleton method possible in Compact Framework VB .NET? If so,
can anyone tell me how to set it up? I've looked all over the web and
have found VB .NET examples, but they're all convoluted and don't
work. I had a real simple one working in C#, but I don't know how to
accurately translate it. Any help would be appreciated.

Thanks
 
http://www.dofactory.com/Patterns/PatternSingleton.aspx

Public Class Singleton

' Fields
Private Shared internalInstance As Singleton

' Constructor
Protected Sub New()
End Sub

' Methods
Public Shared Function Instance() As Singleton
' Uses "Lazy initialization"
If (internalInstance Is Nothing) Then
internalInstance = New Singleton
End If
Return internalInstance
End Function

End Class

[Usage]
Dim s1 As Singleton = Singleton.Instance()
 
Now I feel like an idiot. Since this is my first experience in VB
..NET, I can't even seem to open another form when you click on a
button.

I have a form frmStartup and a button, btnStart. When they tap on the
button, I want the form frmLogin to open using the singleton instance,
but I get nowhere. Can you provide this newbie an example.
 
What's really puzzling is it runs fine in your sample app, the same
code doesn't work in my app!!!
 
Sorry about that, I got it working now, thanks. Will there be any
problem when disposing of forms though, will the instance
automatically be changed to a null value?
 
The Form itself should get disposed if you called the Dispose() method, for
example, but the internal shared reference will still be pointing to a dead
object. So you will need to set the internal instance to Nothing inside the
Dispose() overload. Locate the Dispose() method, shown below, in your code
and update it accordingly.

Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If (disposing) Then
internalInstance = Nothing
End If
MyBase.Dispose(disposing)
End Sub
 
Back
Top