Is implementing a singleton using an auto-property a good idea?

前端 未结 6 1132
时光取名叫无心
时光取名叫无心 2021-01-02 05:13

I recently found out about auto-properties and like them quite a lot. At this moment I am trying to use them everywhere where I can. Not really to just be able to use them e

6条回答
  •  死守一世寂寞
    2021-01-02 05:48

    Wrap up + alternative syntax with lambda style (>= C# 6) aka computed property (aka expression-bodied member):

    The code is functionally fully equivalent to the answer of Jon Skeet, here again with "Instance". I don´t expect kudos for this, but I think this updated wrapup with explanation at one place is it worth, because this C#6 question and answers extend the old closed thread where variations of Singleton have been discussed.

    You could argue the automatic-property-style with an explicitly missing set expresses clearer the intent of a read-only property, but in the end it is style based, and both styles are common in modern C#.

    public sealed class MySingleton
    {
        public static MySingleton Instance => new MySingleton(); // Assure that instantiation is only done once (because of static property) and in threadsafe way, and as this is an alternative style for a readonly-property, there is no setter
        private MySingleton() {} // Assure, that instantiation cannot be done from outside the class        
        static MySingleton() {} // Assure partly lazyness, see below     
    }
    

    Here is all detail and historical reference at one place:

    Discussion about lazyness: http://csharpindepth.com/Articles/General/Beforefieldinit.aspx
    Simplified summary: The above implementation behaves lazy as long as no other static fields/properties are introduced in the class. (But this is an area which can be .NET implementation-dependent.)

    Discussion concerning different implementations of Singleton and thread safety (older C# styles): http://csharpindepth.com/Articles/General/Singleton.aspx

    Original thread (closed): Singleton Pattern for C#

提交回复
热议问题