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.



Concurrency vs Multi-threading vs Asynchronous Programming : Explained

Recently, I was speaking in an event and I asked a question to the audience in between my talk about Asynchronous programming , I found that some of the people were confused between multi-threading and asynchronous programming and some were saying that both are same. So I thought of explaining these terms and add one more term Concurrency. Here there are two concepts involved and both are completely different, First – Synchronous and  Asynchronous programming and second – Single threaded and multi-threaded applications. Each programming model (Synchronous and Asynchronous ) can run in single threaded and multi-threaded environment. Let’s discuss these in detail.

Synchronous Programming model – In this programming model, when a thread assigned to one task and start executing. Then completes the executing task then able to take up another task. In this model, it can not leave the executing task in between to take up some another task. Lte’s discuss how this model works in single and multi-threaded scenario.

Single Threaded – If we have couple of tasks to be worked on and the current system provides a single thread which can work all those, then it takes one by one and process as

singlethreadedHere we can see that we have a thread (Thread 1 ) and four tasks to be completed. Thread starts processing one by one and completes all. (The order in which tasks will be taken up, does not affect the execution, we can have different algorithm which can define the priorities of tasks)

Continue reading

How to Override Finalize method in C#

Being a .NET Developer, you must have basic information about Garbage Collector. Garbage Collector is a boon for .Net developers which takes care of memory management for .NET programs in the background.

But as we know that there are some limitations as well. Garbage collector can collect only managed object. So what about unmanaged objects. Garbage collector cannot clean up unmanaged object properly because these object are not limited to .NET framework and CLR does not have complete control on it. So it is developer’s responsibility to clean up unmanaged resources. It is advised to override the Finalize method (that is a virtual method in Object class) to clean up the unmanaged resources. Garbage collector calls the finalize method of each object (which has overridden Finalize method) while collection process.

So have you ever tried to override the Finalize method in C#? Let’s do that

 public class MyClass
        protected override void Finalize()
            // Do unmanaged resource clean up

For simplicity, I just override the Finalize method. Now let’s build the code.
Ohh.. The above code does not build. It gives the following errorErrorSo if you see the error, it says that do not override Finalize. Instead use destructor.

It means We cannot override Finalize directly in C#.

So what is other way? As in error it suggests to provide destructor. So let us write the destructor (destructor in any class starts with tilde (~)). So now my class looks like

    public class MyClass
            // Do unmanaged resource clean up

            Console.WriteLine("In destructor");

Now let’s build it.
It builds successfully. Now let’s see this class using assembly Reflector.
destuctorSo here our destructor turned into Finalize method. So it means that destructor and Finalize are same in C#. But obviously while writing code in C#, it does not allow to override the Finalize method so we have only option to write destructor for that.

So don’t get confused ever if you see somewhere that say to override Finalize and you are not able to override it. Instead use destructor for that purpose.


How to use two different languages in a .NET Project

Did you ever try to use two languages in some of your project? Or Say you created a Class in VB.NET and used in C# code. As .NET provides us the capability to use multiple languages in same project, even it allows to inherit a VB.NET class in C# Class.If you have not tried earlier then this post will help you in getting practical examples. So Let’s move to the example

In this example, I have created two projects : one is C# Class library project and other is VB console application. My C# class looks like

    public class Person
        public void Print()
            Console.WriteLine("C# - Person's Print method");

It’s perfectly legal to inherit C# class in vb class. So here my vb class looks like

Public Class Student
    Inherits CLSCompliantCsharp.Person

    Public Sub Display()
        Console.WriteLine("I am Student VB class")
    End Sub
End Class

So here I have just added one more method Display in my class. Let’s move to main method

Module Module1
    Sub Main()
        Dim o As New Student()
    End Sub
End Module

Let’s run it and see the output.

NormalSo it is perfectly fine and run as expected. Now let’s add one more method in my person class as

    public class Person
        public void Print()
            Console.WriteLine("C# - Person's Print method");

        public void print()
            Console.WriteLine("C# - Person's print method");

Now I have added one new method with same name print but it’s first letter is small letter. As we know that C# is case sensitive language so having the method with same name with different case, is perfectly legal.So lets build the C# project after making the changes So it is perfectly builds.

Now again move to the VB project and run the code.

Oh.. it throws a error as

errorAs we can see that it is giving error message that Print is ambiguous because for VB.NET Print() and print() are same while for Csharp different.

So How to deal this?

.NET provides us a way to make a library language neutral i e it defines some basic set of rules that can be applied to any library to make neutral. So if you think that your code/dll might be used by different language then you must apply an attribute to the your assembly.

The attribute is CLSCompliant

So if you want to make it a Class library CLSCompliant then add this attribute in the AssemblyInfo.cs file as

[assembly: CLSCompliant(true)]

I have added the above attribute in my C# project and now lets build it (with having two print method as earlier)

CLSComplaintWarningNow if you see that then it is showing an warning that this code is not CLS-Compliant Now you can correct it. Once you remove all the CLS-Complaint warnings and you can take a deep breath. You wont get any complaint if your code is used on any other language in .NET platform.

CLSCompliant attribute also provides more granular approach. It means if you don’t want to make the entire Class library as CLS-Compliant then you apply this attribute at class level as well. Then compiler will apply this attribute on that class only and that can be used by other language applications accordingly.

Hope you all have enjoyed this post.


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


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


What is SecureString ?

In this post, we are going to discuss a class SecureString. Although this class is available since .NET 2.0, but I am sure, many of us would not be knowing or using it. Even I was not aware of this fantastic class few weeks ago. This class can be very useful for you if you are more concerned about your application security.

This class belongs to the namespace System.Security . This class should be used to store the data which is confidential. The text assigned to this string is by default encrypted. This data is also removed as soon as it is not required which in-turn reduces the chances of misuse.

Continue reading

Working with EventViewer using C#

There are several phases of a Application . It does not end with developing the application and deploying it on production servers. Other most important part, any problem surfaces after the deployment, how quickly the problem can be be resolved and according to severity of the issue (if required) a patch can be deployed on production. Apart from this, we also want to get notified on all the issues occurred on production and accordingly analyze and take care in future releases. We can also log other details that could be useful to check the status of Application.

Continue reading