Haitam Zanid Haitam Zanid - 1 month ago 4x
C# Question

One instance of a class at a time

Let's say I have a class called TestClass. I want the application to contain only one instance of this class at a time.

I have a heritable class name Singleton, I use it like this :

public class TestClass : Singleton<TestClass>


And I use it like this

TestClass.Instance // Gives me one instance

The thing is, from time to time, I'll need to re-instantiate the TestClass often, with new parameters etc..

Should I make a static instance and just re-instantiate whenever I want, or is there a better way to do this?

Thanks and sorry.


Singleton is meant to be existing until the app is terminated and shouldn't be re-instanitated. If you want to change any member of this class, create setter method.

For instance, if you have a singleton class and two members in it:

public int Integer1 { get; private set;}
public string String1 { get; private set;}

You can either create two setters or, if these two properties should be changed together, create one method which will set them a given values:

public void SetIntAndString(int int1, string str1)
    Integer1 = int1;
    String1 = str1;

There should never exist any way to delete or modify the class instance object itself.