mardi 23 juillet 2019

Accessing a singleton class in c# with this;

While searching for ways to get an instance of a singleton class i found many different approaches (some simple, some convoluted) but when messing around i found a way to do it which i didn't find anywhere else.

So what i basically do is:

public class Foo
    { 
       public static Foo Invoker;
       public Foo() 
       {
          Invoker = this;

       }
       public void Method1()
       { 
         //.....
       }
    }

And then from another class

public class Foo2
    { 

       public Foo2() 
       {
          //.....

       }
       public void Main()
       {
          var foo = Foo.Invoker;
          //or
          Foo.Invoker.Method1();
       }
    }

My app is single threaded so i don't care about thread safety (should i?) , so are there any other problems that this approach could cause that i am missing?

Aucun commentaire:

Enregistrer un commentaire