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
Related
I was reading this article by Jon Skeet.
In one the samples, he talks about using Lazy<T> to implement singleton pattern.
This is how the code looks:
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()
{
}
}
He does mention at the end
It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.
IsValueCreated indicates whether the lazy object is initialized or not.
I am wondering to ensure this class remains Singleton (only one insteace is created), where and how I would use IsValueCreated property ?
Lazy<T> ensures that only a single instance is ever created, and that instance will be returned when accessing the Value property - however, the creation of such instance is delayed until the first call to Value.
That means, for the given code sample you do not need to check if the instance has already been initialized - this is what Lazy does for you.
However, you have the ability to check so, which could be useful when dealing with a T of IDisposable (or anything that implements this interface). In that case, you can check for IsValueCreated in the dispose method, before trying to call Dispose() on that object (which would in turn uselessly force the creation of the lazy).
I implement a generic singleton class as follows:
public sealed class Lazy<YourClass>
where YourClass : new()
{
static private System.Lazy<YourClass> _Instance = new System.Lazy<YourClass>();
static public YourClass Instance
{
get
{
return _Instance.Value;
}
}
static Lazy(){ } /*'cuz in "Instance" body, "_Instance" is accessed, so it will be initialized before being accessed, and its value will be ensured not to be null. If so, can I remove this static constructor from my code?*/
}
I then can use that in any other class that is intended as singleton. For example:
public class MySingleton{
static public MySingleton Singleton{
get{
return Lazy<MySingleton>.Instance; // will this be null in some circumstances if I remove the static constructro from the above "Lazy" class?
}
}
}
If not implemented correctly, NullReferenceException might be thrown as I used to encounter. The NullReference might be the "Lazy.Instance" or the "_Instance.Value" in the "Instance" get accessor body (I'm not sure about this).
So my question is:
implemented as above (with the static constructor remained in the code), can I be assured that the "Instance" will never be null whenever(even in the typeInitialization of other classes) I access it?
can I remove the static constructor while keeping the #1 assurance?
Thanks!
The static constructor isn't required to ensure that Instance is non-null. However, it is required for actual laziness to be guaranteed, in terms of type initialization.
With the static constructor in place, your type initializer (that creates an instance of System.Lazy<T>) won't be executed unless and until something accesses the Instance property within your Lazy<T> class. (As Peter said in comments, it would be much better to rename the class.)
Without the static constructor present, the type initializer can be executed at any time before the first field access, which means it might happen when a method which conditionally refers to it is JIT-compiled, even if the condition is never satisfied.
In your case, that probably won't make a significant difference, as you wouldn't access the Lazy<T>.Value property. But if you changed your code to create an instance of the class directly, then the static constructor is required to make sure it's genuinely lazy.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between static class and singleton pattern?
i am not able to understabnd the difference b/w static class and singleton class.
in single ton class we make sure we cretae only one object and no more objects are created.
in a the static class also there is no need to create an object we can call the properties and methods directly using the static class name.
here both looks same so whats teh use of using creating single ton class.
any help on this would be great.
In Static class, there is no object. You directly call methods on the static class.
In Singleton, there is an object however, there can only be one instance of it.
Singleton is useful in conditional creation a resources intensive object. For ex, your application might need a connection to remote database. You might want to make it as singleton to limit the number of connections and also to ensure that its only created when required.
Static class and methods are more like utility functions which can be called whenever required.
The difference, obviously, is that on the one hand, you're working in a static context, and on the other, you're dealing with a normal object instance. I'd say the primary consequence of this is that because static members aren't inherited, a static class can't benefit from inheritance or polymorphism, where a singleton can. By working in a static context, you're losing a lot of the object-orientedness of Java.
With a Singleton, we are assured that only one instance of a class (object) is created. This is highly useful when the object is expensive to create, and there's only ever a need for one.
A static class on the other hand, can have no instances of the class created. This is appropriate when methods don't below to a given object and, instead, act on existing objects.
First let's see an example to explain static/instance (code is in as3 but same principle in any languages)
class Blob {
private var i:int=0;
public function Blob() {
i++;
trace("I value : " + i);
}
}
new Blob();
new Blob();
------
output
I 1
I 1
you have 2 instances of your Blob class and i var is create each time.
class StaticBlob {
private static var i:int =0;
public function StaticBlob() {
i++;
trace("I value : " + i);
}
}
new StaticBlob();
new StaticBlob();
--------
output
I 1
I 2
you have 2 instances of your StaticBlob class too but i var is only create once and "keep in memory" for all the instance
Now it's more easy to understand Singleton.
Singleton garantees you to have ONLY ONE INSTANCE of a class (because it uses a static property to keep the reference of your instance and return it).
So it can be use to instanciate one time an object (for example if your object consume too much resource to create)
A singleton class is very different from a static class in that a singleton class can contain static and non static members/properties/methods.
So a singleton object can persist information/state like a normal non static object. Most importantly a singleton is designed to be Thread safe, that is it has a sync root object (generally) that can be used to block threads that are trying to do the same thing.
A static class can only contain static members/properties/members because of this it is impossible to maintain thread safety you cannot lock a static object.
What are the differences between the two? I've only used one kind of constructor and I believe it's the static constructor. Only familiar with C++ and Java.
Static constructor is called the first time your class is referenced i.e.
MyClass.SomeStaticMethod()
Instance constructor is called every time you do 'MyClass dummy = new MyClass()' i.e. create instance of the class
Semantically first is used when you want to ensure that some static state is initialized before it is accessed, the other is used to initialize instance members.
Static constructors allow you to initialize static variables in a class, or do other things needed to do in a class after it's first referenced in your code. They are called only once each time your program runs.
Static constructors are declared with this syntax, and can't be overloaded or have any parameters because they run when your class is referenced by its name:
static MyClass()
{
}
Instance constructors are the ones that are called whenever you create new objects (instances of classes). They're also the ones you normally use in Java and most other object-oriented languages.
You use these to give your new objects their initial state. These can be overloaded, and can take parameters:
public MyClass(int someNumber) : this(someNumber, 0) {}
public MyClass(int someNumber, int someOtherNumber)
{
this.someNumber = someNumber;
this.someOtherNumber = someOtherNumber;
}
Calling code:
MyClass myObject = new MyClass(100, 5);
The static constructor runs only once for all instances or uses of the class. It will run the first time you use the class. Normal constructors run when you instantiate an object of the class.
Everything you should need to know about static constructors can be found here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
I saw this kind of code at work:
class FooPlugin : IPlugin // IPlugin is a Microsoft CRM component, it has something special about it's execution
{
static FooPlugin()
{
SomeObject.StaticFunction(); // The guy who wrote it said it's meaningful to this question but he can't remember why.
}
}
Any idea what does a static modifier on a constructor mean and why in this case it is required?
This is the static initialization of the class.
It would be called when you use a method, a field, a property or anything else of the class. In other word, it would be called the first time you use the class.
See static constructors on MSDN
You can also initialize static stuff here.
In your example it seems that whoever wrote that wanted to call SomeObject.StaticFunction() once before people will use FooPlugin, probably so it will be initialized before using FooPlugin.
Note that there is some performance hit when you use it and visual studio (using code analysis) can let you know that you better off initialize the static fields inline.
See CA1810: Initialize reference type static fields inline on MSDN
It defines the static constructor for the object.
A static constructor is used to
initialize any static data, or to
perform a particular action that needs
performed once only. It is called
automatically before the first
instance is created or any static
members are referenced.
Read more at MSDN - Static Constructors (C#)
I can't say why it's required in your particular case, but the motivation for a static constructor is usually one of these:
All instances of the class need
access to the same instance of an object, or
Initialization of some external object
is a prerequisite for all instances
of the class (seems like the case in your example) or
Initialization of some data structure or service takes takes too much time to do repeatedly (a variation of the first case).
Here's a simpler example of when a static constructor is useful. The following class has some static fields. The first can be initialized inline with its declaration, but the second one can't. Static constructor to the rescue. The key guarantee it provides is that no part of the class can be accessed before the initialization code runs.
class NeedsStaticConstructor
{
private static Size s_size = new Size(100, 100); // can be done inline
private static StringFormat s_format; // more complex initialization needs code
static NeedsStaticConstructor()
{
s_stateTextFormat = new StringFormat(StringFormatFlags.NoWrap);
s_stateTextFormat.Alignment = StringAlignment.Near;
s_stateTextFormat.LineAlignment = StringAlignment.Far;
}
}
A static constructor is used to initialize class-wide (i.e. static) members, as opposed to instance members.
Just to add to the above answers, static constructor (or static blocks as in the case of Java) get executed only once when the class is first loaded in to memory. The objective is to initialize static fields, which otherwise would assume the respective default value of the data type. Sometimes I use static constructors to build an object model that I want to use throughout the life time of the application.