Singleton vs Static class : Key Differences and Usages

The debate about Singleton vs Static is quite old and it is still continuing and there are lots of confusion around this as well. In this post, I am trying to explain these two concepts, key differences and its usages.In this post I will not focus on the basics of Static and Singleton and how to write that. If you are new to these keywords, I will advise you to learn about these first to get more benefited.

So first we are going to understand the characteristics of each . Lets start with static class

Static Class :

  1. Static classes cannot be instantiated so it restricts us in many ways like it cannot implement Interfaces, inherit any class etc.
  2. Any other scenarios where this keyword is required, it cannot be used like indexer etc. Also it cannot be used as method parameter, local variable etc for the same reason.
  3. Static classes can have only static members – constructor, fields, methods, properties, events.
  4. One cannot control when static constructors are called. It’s always earlier than first access of the class. So no parameters can be passed as well.

Internally when compiler compiles static class, it marks it as a abstract and sealed. So that no instance can be created and cannot be extended as well. Now let’s talk about Singleton

Singleton Class :

  1. As name suggests it allows to have only one instance of a class.
  2. The constructor of this class are marked as private so that accidentally one cannot create multiple instances and provides a static function/property which first create one instance and returns the same each time.
  3. As singleton is a normal class, it allows us to leverage all that features of object oriented programming concepts.

Memory Management :

There is much confusion around memory management of static class and Singleton class. In simple words, any class whether it is itself static or any member if marked as static then it would not be collected by Garbage Collector.

Static variables/classes are not stored in normal Heap and there is a separate space in memory to store static resources which holds the static classes and variables.This space is beyond the scope of GC and memory get release only when corresponding process/AppDomain unloads.

Because singleton holds a static reference which cannot be collected by GC so the instance cannot be collected and both (Static and Singleton) gets destroyed with the AppDomain/Process.

Some Key common characteristics :

  • As both of the static and singleton instances are have just one copy in memory throughout the whole application, both used for holding global state in an application.
  • Both are initialized lazily, it means for static classes it is initialized only when accessed first time and for Singleton, it gets created only when it is accessed first time.

The Differences

  1. Very first difference is that Static is a language feature and Singleton is a architectural pattern so both belongs to difference arena altogether.
  2. Now a days everybody is behind using Dependency Injection and Static does not fit there because it is interface driven.
  3. Unit Testing is another topic where you can find some way to create a mock for singleton instances but testing static is a nightmare.
  4. Being singleton is a just another class, it enable you to use Object oriented concepts.

Singleton approach is much more flexible as we can see that from the differences itself. We can use interface with it and implement it in a class and use in our application. If some requirement changes and later we require to change the logic then we can just remove the older implementation and replace with new one without hiccups as long as the interface is same.. Also testing is another key benefit.

Static classes is mainly recommended for having grouping of a bunch of utility methods that can be called independently but again testing could be a problem and benefits of OOP is gone. So most of the time static should be avoided.

Having said that using global variable (like static class or singleton) makes a strong coupling between the global data and all the places where it is used.

Cheers,
Brij

 

Advertisements

[Video] Learn Garbage Collector (Part -5) : Generational Garbage Collector

Hello All,

This is the last part in the series of videos on Garbage Collection process. I have posted four parts earlier and I hope if you’ll see all parts in the series, you’ll get basic end to end understanding of Garbage collection process.

In the first part, I discussed about the basics of Object creation and it’s life cycle. In second video, I included the Garbage Collection steps. Third part included the discussion on Finalization which is one of the important concepts of Garbage Collection Process. In the fourth part, I discussed on the Internals of Finalization. The links of earlier parts are

[Video] Learn Garbage Collector (Part -1) : Object Creation and it’s life cycle

[Video] Learn Garbage Collector (Part -2) : How Garbage Collector runs

[Video] Learn Garbage Collector (Part -3) : What is Finalization

[Video] Learn Garbage Collector (Part -4) : Internals of Finalization

In this post, I am discussing on Garbage Collection Optimization and discussed the Generations in details.

Hope you’ll enjoy it.

Cheers,
Brij

[Video] Learn Garbage Collector (Part -4) : Internals of Finalization

Today, I am going to post fourth part of the series on Garbage Collector. I have published three videos earlier. In first part of the series, I discussed about the basics of Object Creation and it’s life cycle. In second, I talked about the basics of Garbage Collector and How does is run and the steps involve in it. In the third part of the series, I discussed one of the very important concepts of Garbage Collector that is Finalization. Please find the links of earlier part below

[Video] Learn Garbage Collector (Part -1) : Object Creation and it’s life cycle

[Video] Learn Garbage Collector (Part -2) : How Garbage Collector runs

[Video] Learn Garbage Collector (Part -3) : What is Finalization

In today’s Video, I’ll be discussing about the Internals of Finalization. This is little complex but very interesting as well. One similar advice again, prefer watching earlier parts of the video before watching it.

Cheers,
Brij

[Video] Learn Garbage Collector (Part -3) : What is Finalization

Hello All,

This video is third part in the series on Garbage Collector. I have published two earlier parts of the video. In the first part of the video, we discussed how the object gets created, used and destroyed. There are multiple steps involved in it which you must know to understand the Garbage Collector. Please go to the first part of the using the below link.

[Video] Learn Garbage Collector (Part -1) : Object Creation and it’s life cycle

In second part of the video, I discussed about the Garbage Collector and its processing. I discussed the various steps during garbage collection. Please use the below link for second post.

[Video] Learn Garbage Collector (Part -2) : How Garbage Collector runs

In today’s post, I have discussed one of the important concepts of Garbage Collector Finalization and it’s importance. I’ll advise you watch the earlier parts of the video to gain most of the today’s video.

Cheers,
Brij

[Video] Learn Garbage Collector (Part -2) : How Garbage Collector runs

Hello All,

This is second part of the series on Garbage Collector. In my last post, I shared first part of the series. In that video, I talked about the basics of Object creation and talked about it’s life cycle. It is very important for understanding the whole Garbage Collection topic. You can find the link of last post below

[Video] Learn Garbage Collector (Part -1) : Object Creation and it’s life cycle

In today’s video, I have talked about when the Garbage Collector triggers and discussed about it’s processing.

Cheers,
Brij

[Video] Learn Garbage Collector (Part -1) : Object Creation and it’s life cycle

Hello All,

Garbage Collector is one the basic concepts in .NET framework and ironically one of most misunderstood concepts as well. Also, It is also one of the most asked interview questions. To understand the whole concept, one need to understand Object creation and it’s life cycle life cycle and memory management from the application point of view.

I am going to post a series of videos on Garbage Collector and hope this will help you in learning the basics of Garbage Collector. In my first video, I have talked on Object creation and about it’s life cycle.

Hope you’ll enjoy the video and don’t forget to share your feedback.

Cheers,
Brij

Object vs ref Object : Passing a reference type using ref keyword

In this post, I am going to talk about ref keyword in C#. You all must be knowing the basic use of this keyword. But for them who are new to this keyword or C#, will explain the basics.

ref keyword is used to pass the parameter by reference. It means the parameter references the same memory location as the original variable.

As we know that there are two type of variable in C#. One is Value type and other is Reference type. Whenever a value type variable is passed to a method, a copy that variable is created and passed to the method. So let’s see it pictorially

Passed by valueSo when the variable is updated in the called method, then initial variable is not updated but the copy variable gets updated.

Now let’s pass the parameter using ref keyword. So when we pass a value type variable using ref keyword the reference of the variable is passed and both variable names points to same memory location. So when the variable is updated it is available in both method. It can be depicted pictorially as

Pass value using refTill now we passed the value type variable. But when we send other type (reference type) variable to the method the reference is passed so when we update the object in the called method, the updated object gets available to both the method. let’s see the example

For this example,I used an instance of Class type

Typeand the example is

refLet’s come to the real question. What if we pass the instance using ref keyword. When the instance is itself a reference type then what else we get from it. Or they exactly same? Let’s see by example

refref1But if we see the above example, then we get the difference that now variable name points the reference of the reference variable name. When we update the object it updates the same memory location as earlier. By seeing the above example, it seems that there is no difference between passing the reference type variable normally and by ref keyword. But Wait !! Let’s see the screenshot

refref12Now when the UpdateName method get’s executed then what will happen. Let’s see this

refref2

So here after execution of UpdateName both variable name and myName points to null and now the object is available in memory but not accessible from any variable.

But if we pass the object without ref keyword in same method then

ref2So here variable name points to null but myName still points to that object and object is accessible.

So it means as long as we update the object by updating it’s property method etc.,it is same in both case but when we play with the variable name then it makes a difference as we have seen in the above example.

So next time when someone asks that difference by passing the a reference using ref keyword or without ref keyword then you can explain it.

Happy learning!!

Regards,
Brij