If at first you don't succeed, call it version 1.0

Contact Me

Sarvesh Kushwaha
Email : sarveshkushwaha@outlook.com

Total Pageviews

Powered by Blogger.

Google+ Followers

Friday, 20 January 2017

How you can limit a class to create only two instances ? #AspNetInterviewQuestionsSeries

How you can limit a class to create only two(n) instances ?

This is one of my favorite question in an interview.So before watching the answer take a minute and think how you can create a such class .. tough ? Ahan its very easy.

 Answer : The basic idea is create a static property and increment that in constructor every time you are creating an object of that class. And throw an exception when that count is greater than two.

next question which can be ask is :

How you will decrement the count of that property when object is disposed ? Is it thread safe ?

Answer : you will use destructor for that and decrement the count there. Additionally to make it thread safe we can use LOCK keyword or INTERLOCKED keyword.

Below is the running example :

Code Text :

using System;
using System.Threading;
public class Program
 public static void Main()
  TwoInstance T1 = new TwoInstance();
  TwoInstance T2 = new TwoInstance();
  TwoInstance T3 = new TwoInstance(); // this will throw an error :) 
 public class TwoInstance
     private static int countInstances=1; 
  //*if you want to get the count outside then make it 
  //public or create a static int method which will return this property*
  public TwoInstance()
   Console.WriteLine("Instance" + countInstances + "Created");
      //  countInstances++;    *this is the basic thing which came 
   //  into my mind at the time of iterview but this is not thread safe*
   Interlocked.Increment(ref countInstances); 
   // thread safe way to increment the counter or we can use LOCK keyword
    throw new Exception("You cannot create more then two object");
            Interlocked.Decrement(ref countInstances);
Hope my this series will help somebody to get a job :) :) . Happy coding :) 


Post a Comment