-2

I was asked to write Singleton in the interview today. I wrote the below, please note, I used "property set" method to set and then I returned the instance using "get" method. But I see in internet that most places they use only get, meaning, what I did below is wrong? Sorry I dont have VS ide with me to verify it now, so posting it here.

Also, some used sealed class including with private constructor. Why sealed with private cons?

public class Singleton
{
   private static readonly Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
       set
       {
         if(instance == null){
            instance = new Singleton();
         }
       }
       get
       {
                  return instance;
}

   }
}
Jasmine
  • 5,186
  • 16
  • 62
  • 114
  • 1
    Having a `set` like that is misleading IMO. It's clearly not meant to use `value` and ignores it. Everything you do in the setter can be done in the getter (or instance declaration). There are multiple "levels" in which you can create a singleton though. See Skeet's answer here: https://stackoverflow.com/a/2667058/2957232. I'd especially recommend visiting the linked site there as well; it has some excellent in-depth info. – Broots Waymb Jun 21 '19 at 13:59
  • @BrootsWaymb: Thanks. Interviewer said something is missing lol. Well I dont know if its right or wrong at least for a consideration. But if you say this code is wrong (Syntactically or conceptually), then I think I would lose the credibility on this question. I will anyway read the link above – Jasmine Jun 21 '19 at 14:01
  • @BrootsWaymb: I just read his answer, I don't understand why they use "Sealed" keyword in class, secondly, why need of static constructor there. – Jasmine Jun 21 '19 at 14:02
  • 1
    Oh, forgot to mention that the biggest immediate issue with the code, is that `instance` is marked as `readonly`, so it cannot exist in the setter. As for the `sealed` thing, read the link in his answer. It addresses that. – Broots Waymb Jun 21 '19 at 14:03
  • 1
    `Why sealed with private cons?` To stop any other class from newing up a second instance. – mjwills Jun 21 '19 at 14:05
  • @BrootsWaymb: Shit, that was very silly mistake of me, make sense, I couldn't remember that without an IDE and in the stressed interview lol, I had 1.5 hour interview including this written tetsts of programs – Jasmine Jun 21 '19 at 14:06
  • @mjwills: lol you keep answering when I am in a job and also preparing for every interview haha. Thank you. sealed means we can't derive. Now, if I just use "private cons" and not sealed, still will I be able to derive? – Jasmine Jun 21 '19 at 14:08
  • 1
    Yes. You could inherit the class and thus have 'two' of them. – mjwills Jun 21 '19 at 14:09
  • @BrootsWaymb: Sorry again, but when I set that as readonly, still I am able to create instance if its null in the "get" How come? I shouldn't be able to set right if its readonly? – Jasmine Jun 21 '19 at 14:09
  • @mjwills: Thank you so much, that would then make sense to have both. Anyway, I gave the interview, lets see, hope for best :) – Jasmine Jun 21 '19 at 14:10
  • @mjwills: Sure, let me read the link in Skeet's answer too now. Thank you both of you. Pleasant night.Cheers – Jasmine Jun 21 '19 at 14:12

2 Answers2

0

My advice is to try to compile and run the code yourself. It's by far the easiest way to understand how it works.

If you would try to build your code you would get the following error :

Error   CS0198  A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)

In other words, you should instantiate your instance inside the constructor.

Regarding your question, a private constructor is needed to prevent access from outside your class and also it is enough to make sure that other classes cannot inherit from your class. You don't really need the sealed.

You can find a really good summary regarding the singleton pattern @ https://csharpindepth.com/articles/singleton

Andrei T
  • 44
  • 2
  • Thank you for the insights and your time. I dont have IDE in my personal computer. I do have but dont have license key yet. And yes, in my interview, so many questions were in plain A4 sheet and I was asked to write programs for all those questions. I did like 80% for most questions and 100% for few. – Jasmine Jun 21 '19 at 14:24
  • @CamiloTerevinto But they do now. They couldn't have used an IDE to get this answer in the interview, but they don't need to ask a question on SO to get someone to compile their code for them anymore. – Servy Jun 21 '19 at 14:25
  • @Learner The community edition of VS does not require any keys. – Servy Jun 21 '19 at 14:25
  • @Servy: Sure, I will try to download. Thank you. Its midnight 12.26 AM on Saturday lol, I will see if I can download and learn in the days at least, lol it would help me – Jasmine Jun 21 '19 at 14:27
  • 1
    `And yes, in my interview, so many questions were in plain A4 sheet and I was asked to write programs for all those questions` That is an absolutely terrible interview technique. I don't write software without a computer - I surely wouldn't expect someone I want to hire to do so. – mjwills Jun 21 '19 at 14:36
  • @mjwills: Trust me, here at least 5 interviews so far here I have been given white paper to write a program for questions in A4white paper. Only readify asks to write a program at home and host. Or one another company I went to interview few years ago, that gave me computer lol but that was really really tough programs lol. Some other companies recently, gave me online test where we have to write program, no IDE but we can check output I think by running. Thank you again. Goodnight. – Jasmine Jun 21 '19 at 15:17
0

@Learner Since its a interview question and mostly in India they ask to write to Psuedo code to evaluate the candidate coding skills, I try to fit myself in the candidate shoes to give the answer.

Well design patterns has evolved over a period of time with advancements in the programming language and Singleton is not a exception. There are many ways that we can create a Singleton class using C#. I would like to showcase few of the flavors that I can able to recollect

1. Plain vanilla Singleton without Thread-Safety

public sealed class Singleton  
{  
    private Singleton()  
    {  
    }  
    private static Singleton instance = null;  
    public static Singleton Instance  
    {  
        get  
        {  
            if (instance == null)  
            {  
                instance = new Singleton();  
            }  
            return instance;  
        }  
    }  
}

2. Singleton with Thread Saftey

public sealed class Singleton_ThreadLock
{  
    Singleton_ThreadLock()  
    {  
    }  
    private static readonly object padlock = new object();  
    private static Singleton_ThreadLock instance = null;  
    public static Singleton_ThreadLock Instance  
    {  
        get  
        {  
        // Uses the lock to avoid another resource to create the instance in parallel
            lock (padlock)  
            {  
                if (instance == null)  
                {  
                    instance = new Singleton_ThreadLock();  
                }  
                return instance;  
            }  
        }  
    }  
} 

3. Singleton - Double Thread Safe

public sealed class Singleton_DoubleThreadSafe  
{  
    Singleton_DoubleThreadSafe()  
    {  
    }  
    private static readonly object padlock = new object();  
    private static Singleton_DoubleThreadSafe instance = null;  
    public static Singleton_DoubleThreadSafe Instance  
    {  
        get  
        {  
            if (instance == null)  
            {  
                lock (padlock)  
                {  
                    if (instance == null)  
                    {  
                        instance = new Singleton_DoubleThreadSafe();  
                    }  
                }  
            }  
            return instance;  
        }  
    }  
}

4. Singleton - Early Initialization

public sealed class Singleton_EarlyInitialization  
{  
    private static readonly Singleton_EarlyInitialization instance = new Singleton_EarlyInitialization();
    // Explicit static constructor to tell C# compiler  
    // not to mark type as beforefieldinit  
    static Singleton_EarlyInitialization()  
    {  
    }  
    private Singleton_EarlyInitialization()  
    {  
    }  
    public static Singleton_EarlyInitialization Instance  
    {  
        get  
        {  
            return instance;  
        }  
    }  
}  

5. Singleton - Lazy Initialization using .Net 4.0+ Framework

public sealed class Singleton  
{  
    private Singleton()  
    {  
    }  
    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());  
    public static Singleton Instance  
    {  
        get  
        {  
            return lazy.Value;  
        }  
    }  
}

Caveats:

  1. Well there are few people who create instance of the class using reflection (I did in one of my framework) but his can also be avoided. There are few samples in net that can show how to avoid it
  2. Its always best practice to make the Singleton class as sealed as it will restrict developers from inheriting the class.
  3. There are lots of IOC's in the market that can create Singleton instance of a normal class without following the above Singleton implementation.