Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Constructor returning pointer on other object

I would like to know if it's possible that a constructor is able return a pointer on an already instantiated object form the same class? For instance:

    Class Example
    {
            private static Example A = null

            public Example()
            {
                    if (RefTrace == null)
                    {
                            //Here is the initialization of all attributes
                             A = this;
                    }
                      else
                            return A; //To return pointer on already existing instance.
            }


    }

EDIT : This is just the idea, i know that it doesn't work. But I would like to know if there is a way to achieve this?

like image 396
Alexandre M. Avatar asked May 20 '26 09:05

Alexandre M.


1 Answers

What you are trying to implement is a Singleton object. You can read about Singleton pattern here: https://msdn.microsoft.com/en-us/library/ff650316.aspx.

Sample code:

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get 
     {
        if (instance == null)
      {
         instance = new Singleton();
      }
     return instance;
    }
  }

}
like image 170
Huy Hoang Pham Avatar answered May 22 '26 22:05

Huy Hoang Pham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!