I\'ve been studying the Singleton pattern as it is used in the Settings class. Here\'s the relevant code from Settings.Designer.cs for my project AccessTest:
int
There are a great many posts on the singleton pattern but I couldn't find any that address this particular issue. So I thought I'd take a shot at explaining it myself using this example that I created in my secret laboratory with the help of your posts:
namespace MyProject.Properties
{
internal class Singleton
{
// Create an instance of the class itself.
private static Singleton instance = new Singleton();
// Wrap the instance in a public property.
public static Singleton Instance
{
get {return instance;}
}
// Prevent additional references from being created with a private constructor.
private Singleton() { }
// Create a non-static variable.
public string nonStatic = "non static";
}
}
We know the following about this Singleton class:
How, then, is it possible to access 'nonStatic' from outside the class?
The framework resolves the dilemma by endowing the static 'Instance' with magical powers that only exist in a singleton situation: 'Instance' becomes a "bridge" that provides access to any non-statics. Ergo, this form works:
var value = MyProject.Properties.Singleton.Instance.nonStatic;
Note: The pattern used my Microsoft in the Settings.Designer.cs file appears to not be a true singleton because the default constructor allows additional references to be created.