Can I reset a static/shared class?

dr. evil picture dr. evil · May 4, 2009 · Viewed 10k times · Source

I've got a shared class (static in C#) which mostly carries some settings data that any class in the application can read and sometimes write. Also there are some static properties which holds some internal states.

Now I want to revert this class to initial stage of it. With all default variables etc. Assume that the user want to reset the current state and start over without restarting the application.

In a singleton model I'd simply renew it with something like this :

Public Sub Reset() 
    _Instance = New MyClass()
End Sub

However this is not possible in a Shared class. Is there any idea about how can I accomplish this? Or should I switch back to Singleton?

Answer

JaredPar picture JaredPar · May 4, 2009

There is no way to do it in the same way the singleton model you just pointed out. The reason being that there is no backing data store to "reset". What you could do though is simulate this by using an explicit method to initialize all of our data.

Public Module MyClass

  Public Sub Reset()
    Field1 = 42
    Field2 = "foo"
  End Sub

  Public Shared Field1 As Integer
  Public Shared Field2 As String
End Module

Version with a class vs. a module

Public Class MyClass
  Shared Sub New()
    Reset
  End Sub
  Private Sub New()
    ' Prevent instantiation of the class
  End Sub

  Public Sub Reset()
    Field1 = 42
    Field2 = "foo"
  End Sub

  Public Shared Field1 As Integer
  Public Shared Field2 As String
End Class