Trying to understand how static works in this case.

I am looking at some code written by a colleague, and what I expected is not. 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 expected what I could do:

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

and refers to the same instance of this class. What happens, I can only get one .Instance . Something I did not expect. If the Instance property returns a SingletonClass class, why can't I call the Instance property on the returned class, etc. Etc.?

+6
source share
2 answers

If the Instance property returns a SingletonClass class, why can't I call the instance property for the returned class, etc. etc.?

Since you can only access .Instance using the SingletonClass type, not through an instance of this type.

Since Instance is static, you must access it through a type:

 SingletonInstance inst = SingletonInstance.Instance; // Access via type // This fails, because you're accessing it via an instance // inst.Instance 

When you try to link them, you effectively do:

 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; 
+12
source

In code, you return an instance of SingletonClass through an instance, the static type of Singleton

therefore, it will not allow you to do this SingletonClass.Instance.Instance , because SingletonClass.Instance returns an instance of SingletonClass

All that he does not allow you to do this SingletonClass _instance = new SingletonClass(); in this SingletonClass.Instance.Instance

0
source

Source: https://habr.com/ru/post/920708/


All Articles