3

I am in the process of understanding the singleton pattern. I have written a small piece of code here

Program.cs:

class Program
{
    static void Main(string[] args)
    {
        SingleObject objtemp = SingleObject.getInstance();\
        objtemp.showMessage();
    }
}

SingleObject.cs

class SingleObject
{
    static SingleObject obj = new SingleObject();

    private SingleObject()
    {
    }

    public static SingleObject getInstance()
    {
        return obj;
    }

    public void showMessage()
    {
        Console.WriteLine("Hello Message");
    }
}

I am not able to understand what is actually calling the SingleObject() constructor? When I call getInstance() method is it returning the instance correctly?

Saqib Rokadia
  • 629
  • 7
  • 16
user2329702
  • 479
  • 1
  • 4
  • 12
  • 2
    Best way to get into the Singleton pattern is to read this thread : http://csharpindepth.com/Articles/General/Singleton.aspx – Kevin Avignon May 14 '16 at 18:01
  • Static members are automatically initialized when you first use/touch/access the static class. – Chris May 14 '16 at 18:07
  • static SingleObject obj = new SingleObject(); // this is a field. Field initialization occurs (implementation defined) *sometime* before the class is used - by the runtime environment. edit: I believe this can have problems (calling constructor from field initializer) -- the constructor can assume all fields have been initialized, but this won't be the case if you have more fields to be initialized after 'obj' -- they are initialized in the order they are declared. – ABuckau May 14 '16 at 18:19

2 Answers2

0

The basic idea is Your're making the constructor private. So you can't initialize an object of SingleObject from outside. But the static object you create within the class itself can use the private constructor, letting you access it from the outside using a public method.

venkatKA
  • 2,399
  • 1
  • 18
  • 22
0
static SingleObject obj = new SingleObject();

Here you are doing this instantiation. It will be called before first use. Read more here When do static variables get initialized in C#?

Community
  • 1
  • 1
Jakub Szumiato
  • 1,318
  • 1
  • 14
  • 19