2

I do not understand how we can use same property and field type within the class which has not been created yet.

For instance Singleton Design:

public class Singleton
{
    private static Singleton instance;

    private Singleton() {}

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

How this is possible. It has not been declared yet. It is like a recursive function. I can not understand the logic.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189

2 Answers2

0

The property and the field are static. Static members do not need the object of that type to be created. They are like good old procedures and functions which are put to that <classname> namespace.

Dmitri Trofimov
  • 574
  • 2
  • 17
0

Interesting question!

Think of your class as an idea. The compiler knows about your idea within itself, because it is in the same area (namespace). So there is not problem compiling.

A recursive function involves an idea put into practice. If you call a function recursively, you keep placing it onto the stack of the computer which will eventually overflow. 1

When you have a reference to a class (an idea put into practice) within itself, you are creating a pointer to a specific instance of the class (idea). So one pointer can have a reference to another pointer or even a reference to the same pointer within it.

Also, in the case of a static (or Shared in VB) variable, there is only a single instance of the variable for all instance of the class. You don't actually need an instance of your class to call a static member, property or function.

In summary to my ramblings: there is no recursion caused by this pattern because you never cause the class to be constructed from within a call to construct it. If your Instance property tried to call itself to get and instance, that would cause recursion.


  1. As an aside, the remaining space on the stack can be quite small depending on how much you have already placed on the stack. This tail-recursion logic should always be replaced with a loop: Recursive Function Calls Throw StackOverFlowException
Community
  • 1
  • 1
JoelC
  • 3,664
  • 9
  • 33
  • 38