Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

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

You can create a method in the static class which resets the values of all properties. Consider you have a static class

public static class ClassA
{
     public static int id=0;
     public static string name="";

     public static void ResetValues()
     {
         // Here you want to reset to the old initialized value
         id=0;
         name="";
     }
}

Now you can use any of the below approaches from any other class to reset value of a static class

Approach 1 - Calling directly

ClassA.ResetValues();

Approach 2 - Invoking method dynamically from a known namespace and known class

Type t1 = Type.GetType("Namespace1.ClassA");
MethodInfo methodInfo1 = t1.GetMethod("ResetValues");
if (methodInfo1 != null)
{
     object result = null;
     result = methodInfo1.Invoke(null, null);                
}

Approach 3 - Invoking method dynamically from an assembly/set of assemblies

foreach (var Ass in AppDomain.CurrentDomain.GetAssemblies())
{
     // Use the above "If" condition if you want to filter from only one Dll
     if (Ass.ManifestModule.FullyQualifiedName.EndsWith("YourDll.dll"))
     {
            List<Type> lstClasses = Ass.GetTypes().Where(t => t.IsClass && t.IsSealed && t.IsAbstract).ToList();
            foreach (Type type in lstClasses)
            {
                  MethodInfo methodInfo = type.GetMethod("ResetValues");
                  if (methodInfo != null)
                  {
                       object result = null;
                       result = methodInfo.Invoke(null, null);                                
                  }
             }
             break;
    }
}
  • fast approach in terms of execution time is to reset values using a method that resets each value.

  • use reflection if you want to save coding time and write a bug free code. if your static class has many static fields, using reflection reduces chance of missing a property or field.

if your static class has special initialized properties/fields use a method to initialize those fields, i.e first approach.

if your static class has null/default initialized properties/fields use reflection to iterate over all data members and reset them to default value.

use mix of both approaches to coding save time and reduce potential of introducing bugs.

This code resets all fields of MyStaticClass. then calls Init method to initialize fewer rest of fields.

var fields = typeof(MyStaticClass).GetFields(BindingFlags.Static | BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Public);

foreach (var field in fields)
{
    var type = field.GetType();
    field.SetValue(null, null);
}

Init(); // if there are values to be initialized

if your static class has properties, call GetProperties as well and do the same loop to reset them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top