Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reset a static/shared class?

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?

like image 385
dr. evil Avatar asked May 04 '09 17:05

dr. evil


2 Answers

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
like image 190
JaredPar Avatar answered Oct 27 '22 21:10

JaredPar


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.

like image 41
Reed Copsey Avatar answered Oct 27 '22 22:10

Reed Copsey