Skip to main content

C# Singleton, Static Class And Difference Between Them

A singleton stores common data in only on place. A static class is also used to store single-instance data. We save state between usages. We store caches to improve performance. The object must be initialized only once and shared.

Singleton: when we create a singleton class using singleton design pattern try to write that class in a way that there could be only one instance. Below is the code which show how to create a singleton class

using System
public sealed class Singleton
{
                private static volatile  Singleton _instance;
                private static object syncRoot = new object();
                private Singleton(){}
                public static Singleton Instance
                {
                get
{
if(_instance == null)
                {
Lock(syncRoot)
{
                                if(_instance == null)
                                                {
                                                                _instance = new Singleton();
}
                                                                }
}
                                                return _instance;
}
}
}

Notes:-
1.       This approach ensures that only one instance is created and only when the instance is needed.
2.       The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.
3.       This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed.
4.       Making this singleton class sealed will avoid any chance of inheriting this class and making further complicated.

Million Dollar Question: -   So what Benefits we get in a singleton class over a static class?

Answer :- Both singleton class and a static classes are used to have only one instance of that class but there are few benefits which singleton class provides over static class.

1.       Singleton class is lazy load means it load only when it’s required. When we ask for the instance from a static class it will check if there is no instance created it will create it and return the instance but static class object are created and loaded when application starts. Which make application starts slow.
2.       You can implement an interface or derive you Singleton Class from a base class but you can't do the same with static class.
3.       You can have non static in singleton class but your static class should have only static members.
4.       You can pass a singleton class as a parameter to a method but the same you can’t do with static class.
5.       In a static class CLR makes sure there is only one instance of static class, but in case of singleton class we need to write in a way we make sure there is only one instance of singleton class.


Conclusion: - Basically speaking, they are meant for different purposes. A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. A singleton class can be used when you need a class with all the benefit of a normal class and an additional benefit will be that there will be only one instance of this class.

Comments

Popular posts from this blog

Accessing File Stored in Windows Azure Blob Storage Using jQuery

Did you know it was possible to access the Windows Azure Blob Storage directly from JavaScript, for example using jQuery? At first, it sounds obvious, since Blobs are after all accessible from a public UR. But in practice, there is a very big hurdle: the Web browser’s Same Origine Policy or SOP, that restricts JavaScript code to accessing resources originating from the same site the script was loaded from. This means that you will never be able to load a Windows Azure Blob using XMLHttpRequest for example! Fortunately, there is a popular workaround called JSONP (“JSON with Padding”). The idea behind this technique is that the script tag is not submitted to the SOP: an HTML page can thus load a JavaScript file from any site. So, if you expose your data in an “executable” form in JavaScript, a page will be able to load this data using a script tag. For example: <script type=”text/javascript” src=”http://www.sandeepknarware.in/exemple.jsonp”> </script> But how can ...

Support for debugging lambda expressions with Visual Studio 2015

Anyone who uses LINQ (or lambdas in general) and the debugger will quickly discover the dreaded message “Expression cannot contain lambda expressions”. Lack of lambda support has been a limitation of the Visual Studio Debugger ever since Lambdas were added to C# and Visual Basic.  With visual studio 2015 Microsoft has added support for debugging lambda expressions. Let’s first look at an example, and then I’ll walk you through current limitations. Example To try this yourself, create a new C# Console app with this code: using System.Diagnostics; using System.Linq; class Program { static void Main() { float[] values = Enumerable.Range(0, 100).Select(i => (float)i / 10).ToArray(); Debugger.Break(); } } Then compile, start debugging, and add “values.Where(v => (int)v == 3).ToArray()” in the Watch window. You’ll be happy to see the same as what the screenshot above shows you. I am using Visual Studio 2015 Preview and it has some limitati...

gcAllowVeryLargeObjects Element

There are numerous new features coming with .NET 4.5 and here, on this blog, you can find several posts about it. But the feature we are goint to talk about today is very exciting, because we were waiting for it more than 10 years. Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio 2012, and create C# Console Application, like picture below. First lets create simple struct with two double members like example below: 1 2 3 4 5 6 7 8 9 10 11 12 public struct ComplexNumber {      public double Re;      public double Im;      public ComplexNumber( double re, double im)      {    ...