Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand how static is working in this case

Tags:

c#

.net

oop

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?

like image 701
Justin Avatar asked Jul 17 '12 16:07

Justin


1 Answers

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; 
like image 131
Reed Copsey Avatar answered Oct 25 '22 10:10

Reed Copsey