views:

349

answers:

3

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?

+1  A: 

You can't do this in a static class, since there is no instance of a static class.

The two options would be to switch (back) to a singleton.

Alternatively, you could have a method which resets each of the static members of the class.

Reed Copsey
+1  A: 

Maybe a static method that when called, resets all the variable to defaults.

Vincent Ramdhanie
+5  A: 

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
JaredPar
I think this is a reasonable approach, I keep forgetting that I can do "Shared New()"
dr. evil