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

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#

Related

Auto-property initializer Singleton implementation

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.

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..

What are the differences between these options for a simple interface to a field?

I was just staring at the following code and wondered if there was really a need to fill 12 lines of source.
private static IUnityContainer _container;
public static IUnityContainer Container
{
get
{
return _container;
}
set
{
_container = value;
}
}
My thought is, why not just one?
public static IUnityContainer Container;
I think the answer is something like "you can't break encapsulation".. Is this more of a knee jerk reaction to conditioning, or are there some other reasons, subtle or otherwise?
Well, until you don't want to use reflection in some strange ways, like GetType().GetProperty("Container" ...) there are no drawbacks.
It is however considered unclean to expose a field, a property is usually cleaner from a purist point of view.
FxCop will warn you that it is a not nice thing, but there are not drawbacks.
If you want to be short but clean in the same time, you can just use automatic properties:
public static IUnityContainer Container { get; set; }
Automatic properties however works only since compiler version 3.0.
A possible drawback that can happen is if you or someone pass that field byref in some function, for example, Interlocked.Exchange(ref MyClass.MyStaticField, null);
It will not work anymore if you change it with a property in the future, so you should be careful in not passing that field by reference. If you just use a property from the beginning you cannot have this problem.
This problem cannot happen with static readonly fields, they cannot be passed by reference. Using static readonly fields is quite common.
A situation where fields should absolutely not be used instead of properties is when you have a class that inherits MarshalByRefObject, used for remoting (RPC, remote procedure call).
Here I post an example, and as I said, is not your case since the problem is with instance fields and not with static fields.
public class MyClass :
MarshalByRefObject
{
public int MyValue;
}
class Program
{
static void Main(string[] args)
{
var obj = new MyClass();
// This will give you warning CS1690: Accessing a member on 'MyValue' may cause a runtime exception because it is a field of a marshal-by-reference class
Console.WriteLine(obj.MyValue.ToString());
}
}
Remote procedure call works only with methods and properties, for this reason the compiler gives you a warning, since a MarshalByRefObject can be called inside another AppDomain or by another process or another computer via TCP/IP for example.
Personally, I think of it this way. Let's say that at some later time, I want to establish an inavariant that "Container" is never null. If it's defined as a public field, the way to enforce this would be to seek out each and every client that uses it and put code in preventing it from being set to null. If I have it as a property, the same can be accomplished with something like:
private static IUnityContainer _container = new ContainerImpl();
public static IUnityContainer Container
{
get
{
return _container;
}
set
{
_container = value ?? _container;
}
}
Or, you could throw an exception on null value to be more expressive. The specifics aren't important, but the encapsulation angle is.
So, I think that's not simply a knee-jerk reaction, but a pragmatic and reasonable one, especially in the face of the static keyword. Without encapsulation, that's literally just a global variable. At least encapsulating the global state allows the provider some semblance of control over it, rather than leaking control all over the entire application and trusting/forcing clients to be consistent.
One might look at it as a matter of "Don't Repeat Yourself". Any common logic when it comes to a field will necessarily be duplicated all over the place.

Declaring a Class as a Member of itself

I was working in the Microsoft.Ink dll recently using C# and was debugging a problem (which is not related to this) I noticed, that when I was debugging it, ink objects had a strokes object, which had an ink object, which had.... etc.
This confused me, as I was under the assumption you could not do this (I come from a C++ Background)
But I ignored it, solved the problem, and moved on. Today, I run into a similar problem, as I look at a class which had a private member which was the same class as itself.
public sealed class Factory
{
private static Factory instance = new Factory();
}
How is that even possible? I can now call instance.instance.instance.instance...etc. This, as you can imagine, hurts my mortal brain, and I'm sure it can't be good on the computer either. How does the compiler deal with this? And Just how deep does the rabbit hole go?
Because it's static and therefore there is only one copy of the variable instance within the AppDomain.
What you're thinking of is this:
public class Foo
{
private Foo lol = new Foo();
}
Notice, everything here is instance, not static.
As the commenters noted (long ago), this is valid syntactically, but would result in a StackOverflowException being thrown, as the assignment requires construction, and construction creates a new assignment. One triggers the other in a cycle that ends when the call stack reaches its maximum length.
In OP's example, assignment requires construction, but the assignment is triggered by the static constructor, not the instance constructor. The static constructor only executes once within an AppDomain, in order to initialize the class' Type. It isn't triggered by instance construction, and so (in OP's example) won't result in a stack overflow.
it's not necessarily recursive by nature. think of a linked list. or a tree.
class Directory
{
string name;
Directory parentDirectory;
}
It's just allows objects of that class to have an internal reference to another object of that class.
This is a software pattern known as "Singleton".
Some people frown upon the use of the pattern for more reasons than just stated in the question but for better or for worse it is a common pattern in the .NET Framework. You will find Singleton Properties (or fields) on classes that are meant to be instantiated only once. Think of a static Instance property as a global hook upon which to hang an object.
Since this is a class, and not a struct, when you declare a field that is the class, you are only defining a reference to a class. This allows you to keep having references, provided you assign them.
In your case, you're reference allocates a new class, but it is static, so it's only going to do it one time, no matter how many classes you create. The instance constructor runs the first time Factory is used, and will call a single non-static constructor. Doing instance.instance.instance is not allowed, since instance is static. You cannot access a static variable from a member - you need to do Factory.instance.
However, you ~could~ make instance non-static, and have it be a reference to some other "Factory" class, or even a reference to this. In that case, you could chain instance.instance.instance - but it will just follow the references as long as you've set them. Everything works, no problems.
There will only ever be one instance of 'instance' because it is static. The only way you should be able to access it is by calling Factory.instance.
string text = Factory.instance.ToString(); // legal
string text2 = Factory.instance.instance.ToString(); // compiler error
I think you should ask the other way around: Why shouldn't this be possible? Factory is just a type like any type which gets resolved by the compiler.
As most of the answers here point out that this is working only because Factory is a static field, I have added the following sample. Please note that this is a very primitive sample of a chained list (you probably wouldn't implement it that way for various reasons, but I didn't come up with a better example yet). In this example, ChainedListItem is a container for an element of a single-linked list, which contains a field of the very same type to point to the next item in the list. The list has an (empty) head element and the last element is marked by having an empty _nextItem field:
public class ChainedListItem<T>
{
private ChainedListItem<T> _nextItem;
T _content;
public ChainedListItem<T> NextItem
{
get { return _nextItem; }
set { _nextItem = value; }
}
public T Content
{
get { return _content; }
set { _content = value; }
}
public ChainedListItem<T> Add(T content)
{
_nextItem = new ChainedListItem<T>();
_nextItem.Content = content;
return _nextItem;
}
public void Dump()
{
ChainedListItem<T> current = this;
while ((current = current.NextItem) != null)
{
Console.WriteLine(current._content);
}
}
}
class Program
{
static void Main(string[] args)
{
ChainedListItem<int> chainedList = new ChainedListItem<int>();
chainedList.Add(1).Add(2).Add(3);
chainedList.Dump();
}
}
The "rabbit hole" goes as deep as your stack space allows you to make another call to the constructor of the type. If you try to go deeper than that, you will get a stackoverflow exception as with any other recursion.
By the way, the code that you wrote in your answer is showing a very basic implementation of a Singleton which is actually based on having a (private) static member of the same type as the surrounding type.
And, last but not least, such constructs are also perfectly fine in C++.
It is a singleton. Meaning there is really only one instance of the class.
Is that the entire class? Typically in C# you will see a singleton like
public class SomeClass
{
static readonly SomeClass instance = new SomeClass();
public static SomeClass Instance
{
get { return instance; }
}
static SomeClass()
{
}
SomeClass()
{
}
}
I'm not sure how you would even access the instance since it is private. The only thing this would be useful for is a Singleton implementation, but if that is the case you are mission the public property exposing the instance.
This is done all the time is most OO languages. instance is a static member of Factory. There is nothing unusual about this code. It is standard Factory pattern. Do you also have a problem with code like this?
x = x + 1;

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