Auto-property initializer Singleton implementation - c#

So, with the brand new C# 6 we got those neat auto-property initializers. I thought I might as well take advantage of these to make more concise singletons than ever. Apparently someone else got that idea, too.
public sealed class Singleton
{
public static Singleton Instance { get; } = new Singleton();
private Singleton() { /* some initialization code */ }
}
My questions are:
How thread-safe it is?
How lazy it is, or when the instance is actually created? (not a priority, but it would be good for future reference)
Is it a good idea overall?
(it might look similar to this question, but it's not)

Your code will be expanded to the following:
public sealed class Singleton
{
private static readonly Singleton <Instance>k__BackingField = new Singleton();
public static Singleton Instance { get { return <Instance>k__BackingField; } }
private Singleton() { /* some initialization code */ }
}
(<Instance>k__BackingField is the unspeakable name of the compiler-generated field.)
So, the properties of your code will be exactly the same as of the code above. Namely, this pattern is thread-safe and it can be a good idea, depending on circumstances.
Assuming you're not accessing any other static members of this type before accessing Instance, then the exact degree of laziness is up to the runtime. Commonly, it will be something like "the instance is created the first time a method that could access Instance is JIT-compiled", but you don't have any guarantee about this.
If you want to make sure that the instance is created just before Instance is accessed for the first time, add an empty static constructor to your class. (This can have a small negative effect on performance, but that probably won't matter to you.)
Since most of this is not really specific to C# 6, a good source of further information would be Jon Skeet's articles about singletons and static constructors/type initializers.

Related

what is the advantages of Singleton pattern with static constructor?

I have some code as shown below. I guess it is Singleton pattern. Why do I need a static constructor. Also what is the advantages of this? Thanks for your reply ...
public sealed class Myclass
{
static Myclass()
{
Myclass.Application = new Myclass();
}
protected Myclass()
{
}
static Myclass _application;
public static Myclass Application
{
get { return Myclass._application; }
protected set { Myclass._application = value; }
}
string _name;
public string Name
{
get { return _name}
protected set { _name= value; }
}
}
To start with, this class is somewhat odd for having a protected constructor. It's not a fatal flaw given that it's sealed, but it's distinctly odd.
There's a potential difference in timing between this code and the nearly-equivalent use of a static variable initializer:
static readonly Myclass _application = new Myclass();
(There's no need for a setter in this case, of course.)
You can't do that with an automatically implemented property though.
Using static initialization in some form gets you "free" thread-safety - you don't need to do any locking in order to get lazy initialization.
You may find my singleton implementation article interesting for more options.
Usage of a type ctor here is a guarantee that singleton instance will be initialized once. It's more simple that double-checked lock pattern, when implementing lazy singleton initialization, but it has disadvantage the same reason - singleton creation may be very expensive, and singleton may never be used during app lifetime.
There is no immediate advantage in the static constructor as opposed to a lazy-instantiated on get approach, other than thread safety as pointed out by Jon Skeet's answer. This may or may not be relevant in your situation, though you don't specify anything. It just makes the code look different, but is going to result in the same functionality.
The "advantage" of the singleton pattern is that is allows easy access to a single instance of a class, basically a sort of "globally" accessible instance of the class.
I say "advantage" as there are many discussions about the Singleton pattern being an anti-pattern. I am on the fence. In a small application this can function OK and most of the proposed alternative solutions involve Dependency Injection frameworks (often sometimes with the life-span of "Singleton"!), which may be impractical on smaller apps.
Just a note, having a sealed class with protected members is pointless - sealed classes cannot be inherited.
If you write in this way you can use auto property and do not actually implement it.
Say like this:
public sealed class Myclass
{
static Myclass()
{
Myclass.Application = new Myclass();
}
.....
public static Myclass Application {get;set;}
...
}
Basically, there is no any practcal advantage if not like this one: code-style.
You have to create the instance of the class somewhere, and that can either be in a static constructor, or in the property that gets the instance.
Anyhow, it's not a good code example that you have found.
It has protected members even though it's sealed, which only makes the code confusing. They should be private.
If you look at the Name property you will notice that it's impossible to set it, so it will always be null.
static constructor it gets called during the loading of the assembly...
EDIT:
thanks jon I was wrong...
now i understand static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced..

singleton pattern in C# Question

I was researching on the singleton pattern for C# I found this example from the msdn website.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Because the Singleton instance is
referenced by a private static member
variable, the instantiation does not
occur until the class is first
referenced by a call to the Instance
property. This solution therefore
implements a form of the lazy
instantiation property, as in the
Design Patterns form of Singleton.
I am not pretty sure when will the memory will get allocated to
private static readonly Singleton instance
1)Will it happen when the Instance property is called or even before it?
2) I need to force the class to create a new memory sometimes to purge its content. Is it safe to do so using set ?
set
{
instance = null;
}
In the example code you provided, the singleton instance will be created at the time of the first access to the class. This means for your example at the time when Instance gets called for the first time.
More insight you can find in Jon Skeet's article Implementing the Singleton Pattern in C#, see Method 4.
Basically, in order to achieve truly lazy behaviour something like
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton(){}
private Singleton(){}
public static Singleton Instance
{
get { return instance; }
}
}
is enough.
(But anyway, the full and much better overview can be found in the mentioned article.)
EDIT
Actually, as it follows from the mentioned article, the instance is not guaranteed to be created at the first access, because of BeforeFiledInit mark. You need to add an empty static constructor, this way it's guaranteed to be lazy. Otherwise the instance will get created at some unspecified time between the program start and first access. (.NET runtime 2.0 is known to have more eager strategy, so you'll probably not get the lazy behaviour.)
Quoting from the said article:
The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler [...] marks all types which don't have a static constructor [...] as beforefieldinit.
EDIT 2
If you want the singleton object to clean up, you should include this functionality into the class Singleton itself.
Removing the property value will effectively make your class not a singleton any more! Imagine that someone accesses the singleton and gets the singleton instance. After that you set the property to null. The existing object of the Singleton class won't disappear, because there's still a reference to it! So the next time you access the Instance property, yet another instance of the Singleton class would be created. So you lost two things: your object is not a singleton any more (because you have got 2 instances existing at the same time), and the memory hasn't been cleared either.
The singleton instance will be loaded into memory when the class itself is loaded which is when the method which could call it begins execution. The actual line that calls into the class doesn't have to actually execute. This is a very slight distinction but can create hard-to-debug problems when a static constructor or static field initializer can throw an error (which you don't have here).
This is fixed in .NET 4 with the new Lazy<T> implementation.
http://msmvps.com/blogs/jon_skeet/archive/2010/01/26/type-initialization-changes-in-net-4-0.aspx
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
http://csharpindepth.com/Articles/General/Singleton.aspx
The C# specification says:
10.5.5.1 Static field initialization
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.
i.e. They only guarantee you get is that it happens before the instance field is read. But it can happen much earlier.
If you want to guarantee that it that it doesn't run earlier than the first access of the property you'll need to add a static constructor(potentially empty):
The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
· An instance of the class type is created.
· Any of the static members of the class type are referenced.
As a side node: I noticed that when using DI it is rarely necessary to use an actual singleton. Simply telling DI that it should create a single instance is enough. This is very nice if you decide at a later point that you want more than one instance, since then the fact that it's a singleton isn't baked into all the code using it.
It says in the quote you posted:
the instantiation does not occur until
the class is first referenced by a
call to the Instance property
So... Whenever you call .Instance, or at some point before.
Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called.
Read more on MSDN

Singleton and HttpApplicationState

In a web app, I need to have only one instance of a class called ProcessManager. One way is to make it a singleton. The other way is to use the HttpApplicationState to make sure I always access the same instance, like this:
public static ProcessManager ProcessManager
{
get
{
HttpApplicationState applicationState = HttpContext.Current.Application;
if (applicationState["ProcessManager"] == null)
{
applicationState["ProcessManager"] = new ProcessManager();
}
return (ProcessManager)applicationState["ProcessManager"];
}
}
Which method is better and why?
Based on the limited description you've given, I would choose a Singleton, because then it doesn't have a dependency on HttpContext.Current, and can be used outside of the ASP.Net pipeline (for example, when you want to write unit tests.)
(As an aside, when you set something into ApplicationState, you also need to first call Lock() on it, and then Unlock() it after you're done writing to it, to make sure it's thread safe.)
Alternately, allow injection of an HttpContext when you create your ProcessManager, such that you can use it with a mocked HttpContext.
if you plan to implement it as singleton,as per Jon Skeet (a.k.a C# guru),he personally prefers the code below
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
(I'm assuming your ProcessManager constructor is private.)
Making it an actual singleton would be best, because such an approach would make it structurally impossible for other programmers that are maintaining your code to accidentally create multiple instances. There's nothing stopping a consumer from accessing the HttpApplicationState directly and removing and replacing the ProcessManager instance. So you must rely on convention to protect the instance of ProcessManager in HttpApplicationState.
Only if there is an actual use case for multiple instances of the class to exist does it make sense to allow multiple instantiations while relying on convention to protect the instance in HttpApplicationState.

Is implementing a singleton using an auto-property a good idea?

I recently found out about auto-properties and like them quite a lot. At this moment I am trying to use them everywhere where I can. Not really to just be able to use them everywhere, but more to see how well they work in most situations.
Now I am making a singleton and thought:"Hey, let's try auto-properties here as well".
public class MySingleton
{
public static MySingleton MySingleton { get; private set; }
private MySingleton() {}
static MySingleton() { MySingleton = new MySingleton(); }
}
So my question is: "Is it a good idea to implement a singleton like this?"
I am not asking whether a singleton in general is a good idea.
I wouldn't personally do that. I don't like using automatically implemented properties with a private setter that you never call where really you want a read-only property backed by a read-only variable. It's only one more line of code to be more explicit about what you mean:
public sealed class MySingleton
{
private static readonly MySingleton mySingleton;
public static MySingleton MySingleton { get { return mySingleton; } }
private MySingleton() {}
static MySingleton() { mySingleton = new MySingleton(); }
}
This way no-one's even tempted to change the singleton class to reassign either the property or the variable, because the compiler will stop them. They'd have to add a setter and/or make the variable non-readonly, which is a bigger change - one which hopefully they'd reconsider.
In other words:
Yes, it will work.
No, I don't think it's a good idea.
As of C# 6, this is easier with read-only automatically implemented properties though:
public sealed class MySingleton
{
public static MySingleton MySingleton { get; } = new MySingleton();
private MySingleton() {}
static MySingleton() {}
}
I would approach this from a slightly different direction than Jon. Regardless of whether the object is a singleton, is it logically best modeled as a property in the first place?
Properties are supposed to represent... properties. (Captain Obvious strikes again!) You know. Color. Length. Height. Name. Parent. All stuff that you would logically consider to be a property of a thing.
I cannot conceive of a property of an object which is logically a singleton. Maybe you've come up with a scenario that I haven't thought of; I haven't had any Diet Dr. Pepper yet this morning. But I am suspicious that this is an abuse of the model semantics.
Can you describe what the singleton is, and why you believe it to be a property of something?
All that said, I myself use this pattern frequently; usually like this:
class ImmutableStack<T>
{
private static readonly ImmutableStack<T> emptystack = whatever;
public static ImmutableStack<T> Empty { get { return emptystack; } }
...
Is "Empty" logically a property of an immutable stack? No. Here the compelling benefit of being able to say
var stack = ImmutableStack<int>.Empty;
trumps my desire for properties to logically be properties. Saying
var stack = ImmutableStack<int>.GetEmpty();
just seems weird.
Whether it is better in this case to have a readonly field and a regular property, or a static ctor and an autoprop, seems like less of an interesting question than whether to make it a property in the first place. In a "purist" mood I would likely side with Jon and make it a readonly field. But I also frequently use the pattern of making autoprops with private setters for logically immutable objects, just out of laziness.
How's that for taking all sides of a question?
I don't see any reason why this wouldn't be correct. After all, auto-properties are just syntactic sugar for accessors for a private (compiler-generated) backing field.
Sure, I don't see any problem with that.
Auto property? No, I wouldn't but using a setter on a singleton, yes I did. I think you want more control over it than an auto property will give you.
... constructive feedback is more than welcome here, please. This feels like a brave (or foolish) move in this esteemed company ...
My scenario, a WPF app that has a Current Project than can be loaded and saved. The current project settings are used all over the application...
in WPF bindings in the UI so the user can change the settings, hence the INotifyPropertyChanged interface.
I also use Fody.PropertyChanged but that doesn't do static property changes, hence NotifyStaticPropertyChanged.
INotifyPropertyChanged works fine with WPF bindings on the singleton's properties.
An instance of the Settings is [de]serialized using JSON.NET, hence the [JsonIgnore] attribute on the singleton. I validate it before loading it into the singleton or saving it to disk.
the logger is Serilog. You log stuff, right?
the singleton is public with a public getter because WPF bindings only work on public properties. The internal setter doesn't affect it. All the properties of Settings are public for WPF binding.
I left all the "noise" in the code because some may find it useful.
class Settings : INotifyPropertyChanged
{
private static Settings _currentSettings = new Settings();
/// <summary> The one and only Current Settings that is the current Project. </summary>
[JsonIgnore] // so it isn't serialized by JSON.NET
public static Settings CurrentSettings // http://csharpindepth.com/Articles/General/Singleton.aspx
{
get { return _currentSettings; }
// setter is to load new settings into the current settings (using JSON.NET). Hey, it works. Probably not thread-safe.
internal set
{
Log.Verbose("CurrentSettings was reset. Project Name: {projectName}", value.ProjectName);
_currentSettings = value;
_currentSettings.IsChanged = false;
NotifyStaticPropertyChanged("CurrentSettings");
}
}
// http://10rem.net/blog/2011/11/29/wpf-45-binding-and-change-notification-for-static-properties
/// <summary> Fires when the Curent CurrentTvCadSettings is loaded with new settings
/// Event queue for all listeners interested in StaticPropertyChanged events. </summary>
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged = delegate { };
private static void NotifyStaticPropertyChanged(string propertyName)
{
StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
}
// various instance properties including ....
public string ProjectName {get; set;}
[JsonIgnore]
public bool IsChanged { get; set; }
}
usage to set the singleton to a newly loaded project, settings is simply
Settings settings = new Settings();
// load, save, deserialize, set properties, go nuts
Settings.CurrentSettings = settings;
The setter probably isn't thread-safe but I only set it in one place from the UI thread so I'm not scared. You could make it thread safe following the esteemed advice at http://csharpindepth.com/Articles/General/Singleton.aspx
I realise the OP didn't ask about WPF but I think it's relevant to show why you may want to set a singleton. I did it because it is the simplest solution.
Wrap up + alternative syntax with lambda style (>= C# 6) aka computed property (aka expression-bodied member):
The code is functionally fully equivalent to the answer of Jon Skeet, here again with "Instance". I don´t expect kudos for this, but I think this updated wrapup with explanation at one place is it worth, because this C#6 question and answers extend the old closed thread where variations of Singleton have been discussed.
You could argue the automatic-property-style with an explicitly missing set expresses clearer the intent of a read-only property, but in the end it is style based, and both styles are common in modern C#.
public sealed class MySingleton
{
public static MySingleton Instance => new MySingleton(); // Assure that instantiation is only done once (because of static property) and in threadsafe way, and as this is an alternative style for a readonly-property, there is no setter
private MySingleton() {} // Assure, that instantiation cannot be done from outside the class
static MySingleton() {} // Assure partly lazyness, see below
}
Here is all detail and historical reference at one place:
Discussion about lazyness: http://csharpindepth.com/Articles/General/Beforefieldinit.aspx
Simplified summary: The above implementation behaves lazy as long as no other static fields/properties are introduced in the class.
(But this is an area which can be .NET implementation-dependent.)
Discussion concerning different implementations of Singleton and thread safety (older C# styles):
http://csharpindepth.com/Articles/General/Singleton.aspx
Original thread (closed):
Singleton Pattern for C#

Singleton with a public (single-instance) constructor

As an exercise, I'm translating parts of our large and battle-hardened Delphi-framework to C#.
Included in this framework is a generic singleton parent class. Of course, implementing a singleton in C# is fairly easy (there is even a Jon Skeet article, so what more could I wish for), but our Delphi singleton has a slightly different take on the pattern: as opposed to publishing an 'instance' property/method, it has a "fake" constructor that always returns the same instance. The essential characteristic of this approach is that the user of the singleton class doesn't know that he is dealing with a singleton:
as far as they know, they just construct any old class and request some information from it.
I want to accomplish the same thing in C# (as an exercise, so it doesn't have to be production-quality code, evil hackery is fine), but so far I've failed.
Any suggestion to make a simple myInstance = new MyClass(); always return the same instance is most welcome!
Additional info
We are talking a convenience-implementation of the singleton pattern, as offered by the framework. It doesn't necessarely have to be a parent-class, but it does have to assist the developers in creating their own singletons as well. Requiring them to manually redirect all their method calls to the single-instance will not make them overflow with joy. :-)
I'm not really interested in debating whether or not this is the right way to deal with singletons, for now I'm just interested in the finer art of c#-tweaking.
You would do a Proxy (Edit: As Tom points out below, the proper design pattern is Monostate):
public class MyClass {
MyActualClass _actual;
public MyClass() {
_actual = MyActualClass. Instance;
}
public DoStuff() {
_actual.DoStuff();
}
}
internal class MyActualClass {
private MyActualClass {
}
public DoStuff() {
...
}
MyActualClass _instance;
public static Instance {
get {
if(_instance == null)
_instance = new MyActualClass()
return _instance;
}
}
}
....
public static void Main() {
var my1 = new MyClass();
var my2 = new MyClass();
}
my1 != my2 but my1.DoStuff() calls the same instance of the method as my2.DoStuff()
This would be simplified even further if you programmed of an interface only.
Edit: The equality problem could partially be solved by making _actual protected internal and overwriting MyClass.Equals(object obj) to check whether this._actual == obj._actual
I believe the Monostate pattern will give you what you need:
"The Monostate gives us the singularity of state that we so treasure in the Singleton, but without all of the static headaches that come along with it."
More here:
http://jeremyjarrell.com/archive/2008/04/21/88.aspx
As far as I know, this cannot be done for real because of how C# handles object instances. In order for a constructor to be called, the instance has to actually be created, and you can't just "return" another object from a constructor.
The best thing I can come up with (other than using a factory method) is to treat the class internally as a Singleton, and create "dummy" instances that all just point back to that original instance, when created. So for example, in your constructor you would check to see if the singleton has been initialized, and if not, would initialize it, then you would basically just proxy each instance's methods and properties back to the singleton.
In this implementation, the singleton needn't even be necessarily the same class, but you could if you wanted to keep things contained.
Update: One drawback of this approach is that although each instance would behave as a singleton, it would still have its own object reference and therefore you might also want to override Equals() for equality comparisons.
I think you could possibly roll something with Remoting.
Update:
A better way would be to wrap a proper singleton class in a struct or lightweight class.
Create the singleton as a static member and make all methods access the single static instance.
class SingletonWrapper {
private static RealSingleton instance = new RealSingleton();
public void methodA() {
instance.methodA();
}
public String getA() {
return instance.getA();
}
}
(This is actually Java code but C# is similar enough, I think. :)
I don't see how you can, as constructors don't use a return statement. You could clone all of the relevant links to the singleton, but it would have local copies of local variables, and be very messy.
Instead have the constructor check if the singleton is instantiated, and if it has been already, throw an exception, or log a warning to the developer who is using the old style code.
How about using a static function to return an object insted of using the new keyword.
static private m_obj my_obj;
static private bool my_new_obj;
static public m_obj create_m_obj()
{
if (my_new_obj == false)
{
my_new_obj = true;
my_obj = new my_obj();
}
return my_obj;
}
Then you have easy full controle over the creation of the object, if I an not mistaken.

Categories