Justin
Justin

Reputation: 6549

Trying to understand how static is working in this case

I am looking at some code that a coworker wrote and what I expected to happen isn't. Here is the code:

public class SingletonClass
{
    private static readonly SingletonClass _instance = new SingletonClass();

    public static SingletonClass Instance
    {
        get { return _instance; }
    } 

    private SingletonClass()
    {
        //non static properties are set here
        this.connectionString = "bla"
        this.created = System.DateTime.Now;
    }
}

In another class, I would have expected to be able to do:

private SingletonClass sc = SingletonClass.Instance.Instance.Instance.Instance.Instance.Instance;

and it reference the same Instance of that class. What happens is I can only have one .Instance. Something that I did not expect. If the Instance property returns a SingletonClass class, why can't I call the Instance property on that returned class and so on and so on?

Upvotes: 6

Views: 113

Answers (2)

HatSoft
HatSoft

Reputation: 11201

In the code you are returning an instance of SingletonClass via the Instance which is an static of type Singleton

so it wont allow you to do this SingletonClass.Instance.Instance because the SingletonClass.Instance is returning an instance of SingletonClass

All it doing is saving you from doing this SingletonClass _instance = new SingletonClass(); in to this SingletonClass.Instance.Instance

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

If the Instance property returns a SingletonClass class, why can't I call the Instance property on that returned class and so on and so on?

Because you can only access .Instance via the SingletonClass type, not via an instance of that type.

Since Instance is static, you must access it via the type:

SingletonInstance inst = SingletonInstance.Instance; // Access via type

// This fails, because you're accessing it via an instance
// inst.Instance

When you try to chain these, you're effectively doing:

SingletonInstance temp = SingletonInstance.Instance; // Access via type

// ***** BAD CODE BELOW ****
// This fails at compile time, since you're trying to access via an instance
SingletonInstance temp2 = temp.Instance; 

Upvotes: 12

Related Questions