Test Driven Development with TypeScript

Test Driven Development using TypeScript and QUnit.

In this article, I will demonstrate how to write testable code using TypeScript. I assume that the reader is familiar with JavaScript, heard about Typescript and has done or secretly desires to do test driven development.

There is an excellent quick start guide on Typescript that I recommend you to go through before moving ahead.

Project Setup

I am writing the code in Visual Studio 2015 Update 2 (which already has the necessary ingredients to author TypeScript applications). You can also use Visual Studio Code for authoring web applications with TypeScript.

1. Start Visual Studio and Create a new project. From the installed templates, select Html Application With TypeScript template.

Project_template

2. Notice how Visual Studio has done the required scaffolding for your first TypeScript application. In fact, if you press F5 on your keyboard, you will be able to run this application in your browser. Take some time here and see how closely TypeScript resembles an object oriented programming language. You’d see a class, a constructor method etc.

3. When you are done with admiring the beauty of TypeScript, you may select the code in app.ts and delete it. Since we are doing Test Driven Development, we will not be writing any Production code without accompanying tests!

4. In an enterprise project, you’d usually create a new Test Project in the solution. But for the purpose of this article and also to keep things simple in the beginning, I will just create a new folder called as “Tests” under the same project and add a test file in it. .

The goal of the application is to calculate area of different shapes. I usually choose simple applications and simple domains to demonstrate new stuff. This helps in focusing more on the subject rather than focusing on details of the domain.

At this point, I have renamed app.ts to Rectangle.ts and the test file name is RectangleTests.ts

image

Set up for writing Tests

To test TypeScript code, you’d need a testing framework. There are few popular frameworks available like Jasmine and QUnit. For the purpose of this article and also because at the time of writing this article, I couldn’t find any example where typescript is used with QUnit and Chutzpah (more on that later), I decided to write this article using QUnit.

Go ahead and add Qunit-MVC via the package manager console.

   1: Install-Package Qunit-MVC

You’d also need a type definition file for Qunit. The purpose of type definition file (file with extension *.d.ts) is to let TypeScript know about the types that exist in an API. There is a github project called as Definitely Typed,  which provides high quality type definitions for almost all JavaScript APIs.

Run below command to add the type definition file for QUnit.

Install-Package qunit.TypeScript.DefinitelyTyped

Apart from that, you’d need a test runner, where you can see your passing/failing tests. For that I am going to use Chutzpah. To use Chutzpah in Visual studio you need to add an extension. Select Tools>Extensions and Updates and search for Chutzpah. (Since I already have Chutzpah extension added in my VS, I see the option to disable or uninstall it.)

image

Add chutzpah.json file in the root of your project. This json file provides a range of configuration for Chutzpah test runner. For the sake of simplicity, I am configuring the json file with very basic settings:

{
"Compile": {
"Mode": "External",
"Extensions": [ ".ts" ],
"ExtensionsWithNoOutput": [ ".d.ts" ]
}
}

Compile Mode External denotes that Chutzpah test runner can expect compiled .JS file in the default output directory. If you select mode as Executable then you need to provide a powershell or bat file which will convert .ts files to .js file. In this project, I will use tsconfig.json file and configure it in such a way that visual studio will take care of generating a .js file while building (ctrl + shift + b) the project.

Add a file with name tsconfig.json in the root of the project with below settings.

{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
}

With that in place, we are all set to write the tests.

The Red Green Refactor Cycle

Open RectangleTests.ts file and write you first failing test. Below is my first failing test.

/// <reference path="../Scripts/typings/qunit/qunit.d.ts" />
/// <reference path="../Rectangle.ts" />

QUnit.module("RectangleTests.ts Tests");

test("Can create instance of rectangle class with specified length and breadth", () => {

var rectangle = new Rectangle();

ok(rectangle != undefined,
"Assert that rectangle class can be instantiated");

});

There is no need to run tests. The project will not compile because I have not created the Rectangle class yet. A non-compiling class is equivalent to a failing test. So lets write just enough code to make this test pass.

Open Rectangle.ts file and type below code:

class Rectangle {

}

Perfect! This is exactly what we need to make the failing test pass. Lets run the test and confirm if our test is passing.

image

So that’s our Red and Green cycle in TDD. But, what about Refactor? As of now, I do not see any need to refactor the code.

Let’s write the next test. I would like the length and breadth of the rectangle to be passed as constructor argument to the Rectangle class, so lets add another test which passes length and breadth to the Rectangle class.

You’d notice that the project is not compiling because there is no constructor in the Rectangle class which accepts two arguments. To make the project compile, lets add a constructor to the Rectangle class:

class Rectangle {
private breadth: number;
private length: number;

constructor(length: number, breadth: number) {
this.breadth = breadth;
this.length = length;
}
}

Now lets run the tests again.

But hey! Our first test is now failing! Because we do not have any blank constructor in the Rectangle class. At this point we need to do some refactoring!

Do we really need the first test? I would say No, because with the new constructor, we are enforcing a contract that to calculate area of a Rectangle you need to provide length and breadth of the rectangle before hand. So lets delete the first test.

During the refactoring cycle, not only the production code, but the test code can and should be refactored.

Tests deserve to be maintained to the same level of quality as the production code. Indeed, perhaps the tests deserve even more attention than the production code since the quality of the production code depends on the tests;

-Bob Martin

At this point, I would skip demonstrating all the Red Green and refactor cycles that I went through to add the function which calculates the area of a rectangle. The reason I want to skip that is because I want to demonstrate an interesting concept called as “Stubbing”!

Stubbing

For those who are familiar with test driven development would know that unit tests without the ability to stub external dependencies are not of much use. To demonstrate stubbing in our example, I am introducing an external dependency, a webservice which helps in calculating the area of a triangle.

Area of Triangle = 1/2 (height * base)

In our hypothetical world, there exists a service, which if called, provides the height of the triangle. The requirement is that we call a web service to get the height value.

To enable stubbing, we need to add typeMoq framework to the project. Using typeMoq, we can stub external dependencies and also use mocking to verify expectations on method calls.

Install-Package typemoq

Let’s create a class with name TriangleTests.ts and write the first failing test.

/// <reference path="../Scripts/typings/qunit/qunit.d.ts" />
/// <reference path="../Scripts/typemoq.d.ts"/>
/// <reference path="../Triangle.ts"/>

QUnit.module("Triangle test with external dependency");

test("Can create instance of Traingle class",
() => {
var triangle = new Triangle(baseValue);

ok(triangle != undefined, "Assert that the triangle instance is not undefined");
});

This class fails to compile, so lets quickly add Triangle.ts class with a constructor accepting base value:

class Triangle {
private base: number;

constructor(base: number) {
this.base = base;
this.ajaxWrapper = ajaxWrapper;
}

Now, the tests should pass. Next, we need to somehow call a service from this class to get height of the triangle. This means, we need to add a new class which does the Ajax call to a hypothetical service. With that information, lets write our next test.

test("Can create instance of Triangle class with an external dependency",
() => {
var triangle = new Triangle(baseValue, mock.object);

ok(triangle != undefined, "Assert that the triangle instance is not undefined");
});

Notice the usage of mock.object. At this point the project will not compile, so lets fix it and make the tests run. Add an interface in Triangle.ts file.

interface IAjaxWrapper {
        performAjaxCall(): number;
}

and an empty class which implements this interface

class AjaxWrapper implements IAjaxWrapper {
performAjaxCall(): number { throw new Error("Not implemented"); }
}

Notice that we are not writing any implementation for this class. In fact, any attempt to invoke the performAjaxCall method on this class will throw an exception. At this point, we just want our test to pass which is using the mock object to stub an external dependency.

Lets modify the Triangle class and add a new constructor argument:

class Triangle {
private ajaxWrapper: IAjaxWrapper;
private base: number;

constructor(base: number, ajaxWrapper: IAjaxWrapper) {
this.base = base;
this.ajaxWrapper = ajaxWrapper;
}

Notice the usage of IAjaxWrapper interface in the constructor argument, just like how its done in any object oriented language. Add below references in the test class. With these references, we are telling Chutzpah test runner where to find the typemoq library.

/// <chutzpah_reference path="../Scripts/typemoq.js"/>
/// <chutzpah_reference path="../Scripts/underscore.js"/>
/// <chutzpah_reference path="../Scripts/typings/qunit/qunit.js"/>
/// <reference path="../Scripts/typemoq.d.ts"/>

With typemoq referenced in the test class, lets define our mock object.

let mock: TypeMoq.Mock<IAjaxWrapper> = TypeMoq.Mock.ofType<IAjaxWrapper>(AjaxWrapper);

Below is the complete code:

/// <reference path="../Scripts/typings/qunit/qunit.d.ts" />
/// <reference path="../Scripts/typemoq.d.ts"/>
/// <reference path="../Triangle.ts"/>
/// <chutzpah_reference path="../Scripts/typemoq.js"/>
/// <chutzpah_reference path="../Scripts/underscore.js"/>
/// <chutzpah_reference path="../Scripts/typings/qunit/qunit.js"/>

let mock: TypeMoq.Mock<IAjaxWrapper> = TypeMoq.Mock.ofType<IAjaxWrapper>(AjaxWrapper);

QUnit.module("Triangle test with external dependency");

test("Can create instance of Triangle class with an external dependency",
() => {
var triangle = new Triangle(baseValue, mock.object);

ok(triangle != undefined, "Assert that the triangle instance is not undefined");
});

This test will pass!

Let’s write the next test to actually calculate the area of triangle.

let baseValue = 2;

test("Can calculate area of a triangle",
() => {
var heightValue= 10;
mock.setup(x => x.performAjaxCall()).returns((n: number) => heightValue);
var triangle = new Triangle(baseValue, mock.object);

var result = triangle.calculateArea();

ok(result === 10, "Assert that area is calculated correctly.");
});

Notice how the performAjaxCall method is being set up to return a predefined height value. At this point, we do not care how AjaxWrapper is going to fetch the value of triangle’s height, all we know is that the performAjaxCall method is setup to provide that value. Notice we just need an interface, so that we can handle the dependency with fake implementation and move ahead with our tests.

Of course, this test will fail, because calculateArea method does not exist. Let’s fix that and make the test pass. Create a calculateArea method in the Triangle.ts class. Below is the code:

class Triangle {
private ajaxWrapper: IAjaxWrapper;
private base: number;

constructor(base: number, ajaxWrapper: IAjaxWrapper) {
this.base = base;
this.ajaxWrapper = ajaxWrapper;
}

calculateArea(): number {
var height = this.ajaxWrapper.performAjaxCall();
return (1/2) * this.base * height;
}
}

This should be enough for the tests to pass.

With that, I’d conclude this article. Hope the article was helpful.

Quick Tips

1. Chutzpah can show test results on a web page. To view your tests in a browser, right click on the test file and from the context menu Select Run Chutzpah with > Debugger. You can also put breakpoints and debug your tests.

image

2. You can check the code coverage of your TypeScript code. Below is the code coverage of TriangleTests.ts

image

The code for this demonstration can be found at my github repository.

A WCF Chat Service & Client

I attended a interview recently for which the pre-requisite was to develop a chat application using WCF as part of a code challenge. The requirement was quite simple, so instead of taking the usual route of creating a WCF service and adding its reference to a client application, I decided to hand code everything without any configuration or service references!

Of course the  assumption here is that the service and client applications are owned by a single company/team so that the contracts can be shared between the service and client.

The complete code is available in my Github account.

The Problem Statement
Goal - Create a Chat Server and Client application using 
.NET 4.0/4.5 with WCF as the communication mechanism. 
The Chat Server should be a standalone application and 
the Chat Client should be a standalone application with 
a basic UI for users to interact and exchange messages 
through the Chat server. Stability of the code is a 
must-have and it should be ensured that the 
Server/Client do not crash during operation to 
maintain quality user experience. 

The basic functionality to be supported is as follows: 

1. The chat server should open up a TCP port for
 listening to incoming client requests. 

2. The server should be able to handle at 
least 2 distinct clients’ communication in parallel. 

3. On successful connection with the server, 
the chat client should be able to send plain text 
messages to the server. 

4. The server should be able to respond to each 
message by a static message "Hello!" appended 
with the server's timestamp. 

5. Both chat clients should be able to communicate 
with the server without the messages of either being 
visible to the other one. 

The Approach

Since the service contract has to be shared between the service and client the best place to create the service contract is in a common library project. I have created a “contract” folder which has few more sub folders having contracts for service, response, request,  fault and a contract for callback service (more on this later).

image

The Duplex Message Exchange Pattern via Callbacks

IEAChatService.cs is the service contract defined as shown below

 [ServiceContract(
        SessionMode = SessionMode.Required, 
        CallbackContract= typeof(IChatCallback))]
 public interface IEAChatService

I have defined a CallbackContract for this service contract. This callback contract interface is defined in IChatCallback.cs and is implemented by the client application (EA.Client.EAChat.UI).

    [ServiceContract]
    public interface IChatCallback
    {
        [OperationContract(IsOneWay=true)]
        void RefreshUserList(List<User> onlineUsers);

        [OperationContract]
        void ResponseMessage(ResponsePacket response);
    }

This contract is called as a duplex service contract. Duplex service contract is a message exchange pattern where service as well as client can send messages to other independently. Since this interface is implemented by client (EA.Client.EAChat.UI), the service can directly call the client methods. In this case, whenever a new user enters the chat room the Register  method of the EAChatService.cs calls the callback method RefreshUserList on the client, so that client can refresh the user interface and show the name of the newly entered user in the list of users of the chat room. Below is the relevant piece of code.

       public void Register(User userHandle)
        {
            try
            {
						//---irrelevant code removed ---------
                       foreach (KeyValuePair<string, IChatCallback> kvp in registeredUser)
                        {
                            IChatCallback callback = kvp.Value;
                            callback.RefreshUserList(onlineUsers);
                        }
                    }

                }
               // ---irrelevant code removed ---------

            }
            catch (UserHandleInUseException uEx)
            {
                log.Error("User handle is alread in use. Error Detail: " + uEx.Message);
                throw;

            }
            
            
        }
The Service Side Code

EAChatService.cs inherits from ServiceBase.cs. ServiceBase class has some common properties used why the EAChatService class. For instance, the ServiceBase class has a protected getter property  which returns the channel to the client instance which called the operation currently. Below is the code snippet.

      protected IChatCallback Callback
       {
           get
           {
               return OperationContext.Current.GetCallbackChannel<IChatCallback>();
           }
       }

 

ServiceBase class also has a protected dictionary for registeredUsers which stores the userID and the corresponding Callback as a keyvalue pair in the dictionary object. Since multiple users may call the Register method at once, the critical section of adding users in the dictionary is synchronized using a lock. below is the complete code of register method.

       public void Register(User userHandle)
        {
            try
            {
                if (!registeredUser.ContainsKey(userHandle.UserId) &&
                    !registeredUser.ContainsValue(Callback))
                {
                    lock (syncObject)
                    {
                        registeredUser.Add(userHandle.UserId, Callback);
                        onlineUsers.Add(userHandle);

                        foreach (KeyValuePair<string, IChatCallback> kvp in registeredUser)
                        {
                            IChatCallback callback = kvp.Value;
                            callback.RefreshUserList(onlineUsers);
                        }
                    }

                }
                else
                {
                    throw new UserHandleInUseException(ServiceFaultCode.HANDLE_IN_USE, "User with this handle already exist. Please choose a different handle.");
                }
            }
            catch (UserHandleInUseException uEx)
            {
                log.Error("User handle is alread in use. Error Detail: " + uEx.Message);
                throw;

            }
            
            
        }
The Client Code

The client code is implemented in the ChatWindow cliass. The ChatWindow  class has a SynchronizationContext which is used to marshal messages from one thread to another thread. You must be wondering, why do we need to marshal messages from one thread to another. The reason is that the client UI runs on a separate thread and the duplex message from the WCF service is delivered to the client application via another thread. Now the message sent from WCF service as part of duplex call cannot be directly used by the client UI. To enable the message transmission between the UI thread and callback thread, we use the UI thread’s SynchronizationContext and call its Post method to pass the message. I am using Unity container to hold and resolve instances of SynchronizationContext object. Below is the implementation of RefreshUserList callback method which demonstrates the SynchronizationContext usage.

       public void RefreshUserList(List<User> onlineUsers)
        {
            ClearOnlineUserList();

            foreach (User user in onlineUsers)
            {

                SendOrPostCallback callback =
                delegate(object state)
                {
                    this.OnlineUserListBox.Items.Add(user.UserId);
                };

                _uiSyncContext = (SynchronizationContext)container.Resolve(typeof(SynchronizationContext));
                _uiSyncContext.Post(callback, user.UserId);
            }
        }
The WCF endpoint & Hosting

The WCF endpoint is configured programmatically in the EA.Host.ServiceHostEngine project where we have the logic of hosting the WCF service as well.

I have defined an Interface IHostScheme.cs which has the declaration of  Host method and this interface is implemented by NetTcpHost.cs. Since one of the assumptions is that this chat application works in intranet, I choseto use NetTcp binding for the communication. In future if we decide to make to this chat application work in extranet then we can create another class implementing the IHostScheme interface with appropriate binding implementation.

Lets look at the NetTcpScheme.cs class.

    public class NetTcpHost : IHostScheme
    {
        public ServiceHost Host(string portNumber, bool enableMetaData)
        {
            Type contractType = typeof(IEAChatService);
            Type serviceType = typeof(EAChatService);

            Uri baseAddress = GetBaseAddress(portNumber);

            ServiceHost serviceHost = new ServiceHost(serviceType, baseAddress);
            serviceHost.AddServiceEndpoint(contractType, new NetTcpBinding(), baseAddress.AbsoluteUri);

            ServiceMetadataBehavior metaDataBehavior = new ServiceMetadataBehavior();
            metaDataBehavior.HttpGetEnabled = false;
            serviceHost.Description.Behaviors.Add(metaDataBehavior);

            if (enableMetaData)
            {
                serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
              MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
            }
            

            return serviceHost;
        }

        private Uri GetBaseAddress(string portNumber)
        {
            string prefix = ConfigurationManager.AppSettings["nettcp_prefix"];
            string chatServicePath = ConfigurationManager.AppSettings["EAChatServicePath"];

            return new Uri(prefix + portNumber + chatServicePath);


        }
    }

The code is pretty much self explanatory. This class is responsible for creating a ServiceHost and a ServiceEndpoint. To create a ServiceHost, we need the type of Service contract and to create a service endpoint which will be hosted by the ServiceHost, we need the contract’s type, address (along with the port) where we will host the service and binding is set to NetTcpBinding because that’s one of the requirement in the problem statement that communication has to take place over tcp port.

I have made HttpGetEnabled property of ServiceMetadataBehavior to false, as I don’t se any benefit of exposing the wsdl over http for our application. However, MEX endpoint is made configurable, so that if in future we wish to create a new client and create a proxy using svcutil for communication, we could do so easily.

That’s it! There are other utility projects and relatively less interesting code in the solution, so I will skip the remaining details.

Feel free to use the code and modify it according to your requirements. The code is available  in my Github account.

If you have any queries, feel free to ask in the comments section.

Mobile Push Notification Service – Design Approach (Part 1)

A high level design of Mobile push notification service.

Overview of Push Notifications

In this article, I am going to design the architecture for implementing push notifications for you mobile application. This part only has design and architecture information, code will be covered in Part 2.

If you are new to push notifications, please read wiki article about the technology and also about GCM and APN services.

Below diagram depicts a high level overview of device registration process.

DeviceReg

  1. Device sends sender ID, application ID to GCM server for registration.
  2. Upon registration Cloud Service (GCM/APNs) sends a unique registration ID to the device.
  3. After receiving the registration ID from the cloud service the device will forward the registration ID to the Push Notification Web Service.
  4. The Push Notification web service will store the registration ID in a local database for later use.

a. Whenever Push Notification service needs to send the notification, it has to call GCM/APN service with registration ID of the device which is stored in the database.

b. GCM/APN service will deliver the notification to respective mobile device based on the registration ID.

Push Notification service would require an outbound internet connection to send messages to cloud services. Make sure to open two outbound ports on your push notification server.

Push Notification Components

You would need to implement two components:

  1. Push Notification Web Service

Push notification web service could be a rest service. Bare minimum the web service should have two functionalities. One, to register new device and Second, to unregister a device.

  1. Push Notification Windows Service.

You need to implement a windows service which could spawn multiple threads to listen to a messaging queue at a specified address. This service should be capable to pick up messages as and when it arrives to the messaging queue. The service will then query the local database and get a list of eligible devices which should receive the notification message and communicate with the cloud messaging services to get the notifications delivered.

Push Notification Windows service is a Microsoft Windows® terminology. On non-windows platform this windows service will be a process which will be initiated with a start-up batch file which could be hooked up with tomcat initialization process.

Push Notification Architecture

Diagram below depicts the push notification architecture at high level.

HLD

  1. As depicted in the diagram above, the first step is get the unique device ID from the cloud messaging service. The mobile application should make a call to the cloud messaging service every time it is launched. It is important to make this call every time as it may so happen that the unique device ID assigned earlier has now expired.
  2. Second step is to call the Push Notification web service from the mobile application and include the unique device ID (received from cloud messaging service) in the payload. You may want to pass some additional information like the device type, device operating system etc in the payload. A sample payload JSON is shown below:

    DevicePayload:{
    
    deviceId:'APA9sdsdA',
    
    deviceType:'mobile/tablet',
    
    deviceOS:'android/apple',
    
    userID:'xyz@gmail.com',
    
    }
    
    
  3. Push notification web service will persist the payload in a local database.
  4. Core product which is responsible for generating events per user will create notification messages and publish it to the Messaging Queue.
  5. Push notification windows service’s functionality is to constantly poll the Messaging Queue and pull any new message that arrives to the queue. The service should then query the local database to get the device id associated with the user id for which the notification was generated.
  6. With the fetched device id, the windows service will then communicate with cloud messaging services (GCM/APN).

This is the architecture at high level to design push notification service for your mobile application. In the next article (Part-2), I will cover the code required to communicate with the cloud messaging services.

A Thread Safe Singleton Class in .NET

In this post I will demonstrate creating a singleton class in .Net that is thread safe. As usual the singleton class should have a private constructor as shown below so that any other class cannot “directly” create an instance of our singleton class.

Apart from that, I have created two global variables, one to hold the instance of the Singleton class and another one of type object which will be used later for synchronization between threads (more on that later).

    static SingletonSample _instance;
    static readonly object _synchronizer = new object();
    /// &amp;lt;summary&amp;gt;
    /// Private C'tor, so that this class cannot be instantited by other classes directly
    /// &amp;lt;/summary&amp;gt;
    private SingletonSample()
    {

    }

Method 1 – Using synchronization lock

 

GetInstance is a public static method, this method is the only way by which any other class can get instance of the singleton class.

Below code snippet uses double check pattern before creating the instance of the singleton class. The first If statement, if true, will give the instance of Singleton class instantly. However, if _instance variable is null then program will enter a critical section (the lock statement) synchronized using a global object (_synchronizer). Inside the critical section, I am checking the _instance  variable again if it is null (double check), if it is, then we finally create the instance of the class.

One interesting point to note here is, I am not creating the instance directly and returning it back. I am first assigning the class reference into a temporary object of type SingletonClass (tempInstance) and then doing a  Volatile write on the actual instance variable (_instance).

 

 

        /// &amp;lt;summary&amp;gt;
        /// Method is responsible for providing instance of this class.
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;returns&amp;gt;Instance of SingleTonSample class&amp;lt;/returns&amp;gt;
        public static SingletonSample GetInstance()
        {
            //If instance is available return that.
            if (_instance != null)
                return _instance;

            //Critical section. Ony one thread can enter at a time.
            lock(_synchronizer)
            {
                //Check again if the instance in null
                if(_instance == null)
                {
                    SingletonSample tempInstance = new SingletonSample();
                    //Volatile write to make sure that _instance is 
                    //populated with tempInstance reference without any compiler optimization.
                    Volatile.Write(ref _instance, tempInstance);
                }
            }

            return _instance;
        }

The problem with this approach is that if this method is used in a highly parallel system, the critical section will cause all threads to do nothing but wait for an instance of Singleton class to be created. However, this will happen only once when the first instance is getting created, but still, this is wasteful of the resources.

Below is another, more efficient way of creating a singleton which neither uses double check pattern nor it has a critical section for thread synchronization.

Method 2 – Without Critical Section or Double Check

Below method will allow multiple threads to create instance of Singleton class, but Interlocked class’s CompareExchange will make sure that only one instance is assigned to _instance variable. Objects created by other  threads and not assigned to _instance variable will soon become Orphan and  will be garbage collected at a later point of time by the CLR.

        /// &amp;lt;summary&amp;gt;
        /// Method is responsible for providing instance of this class without critical section
        /// or double check pattern.
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;returns&amp;gt;Instance of SingletonSample class&amp;lt;/returns&amp;gt;
        public static SingletonSample GetInstance()
        {
            //If instance is available return that.
            if (_instance != null)
                return _instance;
            
            SingletonSample tempInstance = new SingletonSample();
            /*Multiple threads will create singleton object, but only 
            *one will be asssgined to _instance variable. Rest others will be 
            *GC'd (Garbage Collected) later at some point of time. 
            */
            Interlocked.CompareExchange(ref _instance, tempInstance,null);
            
            return _instance;
        }

Both methods are thread safe. However, method 2 is marginally more efficient and lean as compared to the first one.