Probably every developer sometimes heard about the singleton pattern. I’ll be not far from truth that you’re probably writing it like this:
class Foo1
{
private static Foo1 _instance;
public static Foo1 Instance
{
get
{
if (_instance == null)
_instance = new Foo1();
return _instance;
}
}
}
I do it same way. But today I seen little bit different way. It’s using the C# coalesing operator and some C-like magic syntax.
class Foo2
{
private static Foo2 _instance;
public static Foo2 Instance
{
get
{
return _instance ?? (_instance = new Foo2());
}
}
}
Looks cool, isn’t it? On the other hand I’ll probably use the first one, as it’s more readable, at least for me.




#1 by André on 26.8.2009 - 22:22
Quote
Don’t use this. They are both the same and not thread safe.
When I use singleton, I prefer version 4 from here:
http://www.yoda.arachsys.com/csharp/singleton.html
#2 by cincura.net on 26.8.2009 - 22:32
Quote
I don’t care about thread safety in this example. In fact when I need thread safety I often need more than this (i.e. fine grained locking in methods too etc.).
#3 by alvar on 27.8.2009 - 16:10
Quote
The simplest singleton:
public sealed class BestSingleton
{
/// Best implementation of singleton pattern.
/// What we really care about is that we get the instance created either on or just before the
/// first call to (in this case) the Instance property, and that we have a defined initialization order
/// for static variables in a class. With the .NET Framework, this is exactly the behavior we get.
/// The Framework, during the JIT process, will initialize the static property when (and only when) any method
/// uses this static property. If the property is not used, then the instance is not created.
/// More precisely, what happens during JIT is that the class gets constructed and loaded when any static member
/// of the class is used by any caller. In this case the result is the same.
/// What about thread-safe initialization? The Framework addresses this too. The Framework internally guarantees
/// thread safety on static type initialization. In other words, in the example above, there is only one instance
/// that would ever be created of the Singleton class. Note also that the property field used to hold the instance
/// of the class is called Instance. This choice better illustrates that this value is an instance of the class.
/// In the Framework itself there are several classes that use this type of singleton, although the property name used
/// is called Value instead. The concept is exactly the same.
///
static BestSingleton(){} // Removes beforefieldinit flag from the type
public static readonly BestSingleton Instance = new BestSingleton();
private BestSingleton() {/*construct the only instance*/}
}