9

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 everywhere, but more to see how well they work in most situations.

Now I am making a singleton and thought:"Hey, let's try auto-properties here as well".

public class MySingleton
{
    public static MySingleton MySingleton { get; private set; }

    private MySingleton() {}

    static MySingleton() { MySingleton = new MySingleton(); }
}

So my question is: "Is it a good idea to implement a singleton like this?"

I am not asking whether a singleton in general is a good idea.

Matthijs Wessels
  • 6,530
  • 8
  • 60
  • 103

6 Answers6

16

I wouldn't personally do that. I don't like using automatically implemented properties with a private setter that you never call where really you want a read-only property backed by a read-only variable. It's only one more line of code to be more explicit about what you mean:

public sealed class MySingleton
{
    private static readonly MySingleton mySingleton;
    public static MySingleton MySingleton { get { return mySingleton; } }

    private MySingleton() {}

    static MySingleton() { mySingleton = new MySingleton(); }
}

This way no-one's even tempted to change the singleton class to reassign either the property or the variable, because the compiler will stop them. They'd have to add a setter and/or make the variable non-readonly, which is a bigger change - one which hopefully they'd reconsider.

In other words:

  • Yes, it will work.
  • No, I don't think it's a good idea.

As of C# 6, this is easier with read-only automatically implemented properties though:

public sealed class MySingleton
{
    public static MySingleton MySingleton { get; } = new MySingleton();    
    private MySingleton() {}         
    static MySingleton() {}
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I strongly disagree. Auto-properties were invented to make code more succinct, which makes code more readable. The argument that it's a little harder for others to mess up your design is not very convincing IMHO. – Philippe Leybaert Jan 22 '10 at 13:17
  • 7
    @Philippe: Auto-properties were invented to make code more succinct *where the replacement code is equivalent to the original*. There's no such equivalence here: you're replacing a read-only property with a read-write one, even though it's got a private setter. This may seem trivial, but I rather like my code to express my intentions - and my intention here would be that the value can only be set once. The automatically implemented property expresses a different intention. – Jon Skeet Jan 22 '10 at 13:24
  • You have a point about the "intention" of the setter, but in the end, to the consumer of the class, there is no difference whatsoever. Having an auto-property with a private setter is excactly the same as having a read-only property with a private backing field. Sure, it compiles to different code, but it's essentially the same from the point of view of the consumer of the class. Now I have to slap myself, because I've never liked auto-properties and now I'm defending its use (but that's a topic for another question I guess) – Philippe Leybaert Jan 22 '10 at 13:41
  • 1
    @Philippe: So as long as the API is all right to the *consumer*, it doesn't matter what the implementation is like? What about the maintainer? I like my code to document intention to the next person who's going to look at the source code, not just consumers. – Jon Skeet Jan 22 '10 at 13:59
  • In the case of a well-known pattern, the "intent" is usually very clear, so I don't think it's an issue here. My point really is: "Less code" is usually "Better code", as long as it results in better readability. But I don't want to start an endless argument. Your points are valid, but in this specific case, I think the OP's code is more readable. – Philippe Leybaert Jan 22 '10 at 14:12
  • 1
    Hello - the new syntactic sugar in C# makes it OK to se the auto property like that, doesn't it? `public static SomeSingleton Instance { get; } = new SomeSingleton();` – Bartosz Jun 28 '16 at 07:50
  • @Bartosz: Yes, that would be fine as of C# 6. Will edit. – Jon Skeet Jun 28 '16 at 08:22
  • @JonSkeet does the auto-property interfere with thread safety/laziness? Just reading through your _C# in Depth_ companion website and looking at [Solution no. 4](http://csharpindepth.com/Articles/General/Singleton.aspx) – Thomas Feb 24 '17 at 18:13
  • 1
    @Thomas: Nope, it shouldn't do - it's a simple property backed by a read-only field. – Jon Skeet Feb 24 '17 at 21:57
11

I would approach this from a slightly different direction than Jon. Regardless of whether the object is a singleton, is it logically best modeled as a property in the first place?

Properties are supposed to represent... properties. (Captain Obvious strikes again!) You know. Color. Length. Height. Name. Parent. All stuff that you would logically consider to be a property of a thing.

I cannot conceive of a property of an object which is logically a singleton. Maybe you've come up with a scenario that I haven't thought of; I haven't had any Diet Dr. Pepper yet this morning. But I am suspicious that this is an abuse of the model semantics.

Can you describe what the singleton is, and why you believe it to be a property of something?

All that said, I myself use this pattern frequently; usually like this:

class ImmutableStack<T>
{
    private static readonly ImmutableStack<T> emptystack = whatever;
    public static ImmutableStack<T> Empty { get { return emptystack; } }
    ...

Is "Empty" logically a property of an immutable stack? No. Here the compelling benefit of being able to say

var stack = ImmutableStack<int>.Empty;

trumps my desire for properties to logically be properties. Saying

var stack = ImmutableStack<int>.GetEmpty();

just seems weird.

Whether it is better in this case to have a readonly field and a regular property, or a static ctor and an autoprop, seems like less of an interesting question than whether to make it a property in the first place. In a "purist" mood I would likely side with Jon and make it a readonly field. But I also frequently use the pattern of making autoprops with private setters for logically immutable objects, just out of laziness.

How's that for taking all sides of a question?

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • Hmm, interesting. I never really considered properties in that manner. For me they have always just been a replacement for accessor methods. In a way I viewed accessor methods as a way to improve upon public fields (partially hide, put in interface, add some checking info). And then properties to be able to get a more intuitive way than getters and setters. So for me a property never has to logically be a property of the things the class represents. For me a property is just how a field looks from the outside. – Matthijs Wessels Jan 22 '10 at 19:17
  • Could you elaborate on the benefit of property-like syntax in your `ImmutableStack.Empty` example? I'd like to better understand what benefit you achieve here, particularly since in LINQ `Enumerable.Empty()` is similar to the type of syntax you avoid in that example. – LBushkin Jan 22 '10 at 22:30
  • @LBushkin -- I suppose "Empty" vs "Empty()" vs "GetEmpty()" are all pretty small differences. I think "compelling benefit" was an exaggeration! :-) – Eric Lippert Jan 23 '10 at 15:07
0

I don't see any reason why this wouldn't be correct. After all, auto-properties are just syntactic sugar for accessors for a private (compiler-generated) backing field.

Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
0

Sure, I don't see any problem with that.

Dave Markle
  • 95,573
  • 20
  • 147
  • 170
0

Auto property? No, I wouldn't but using a setter on a singleton, yes I did. I think you want more control over it than an auto property will give you.

... constructive feedback is more than welcome here, please. This feels like a brave (or foolish) move in this esteemed company ...

My scenario, a WPF app that has a Current Project than can be loaded and saved. The current project settings are used all over the application...

  • in WPF bindings in the UI so the user can change the settings, hence the INotifyPropertyChanged interface.
  • I also use Fody.PropertyChanged but that doesn't do static property changes, hence NotifyStaticPropertyChanged.
  • INotifyPropertyChanged works fine with WPF bindings on the singleton's properties.
  • An instance of the Settings is [de]serialized using JSON.NET, hence the [JsonIgnore] attribute on the singleton. I validate it before loading it into the singleton or saving it to disk.
  • the logger is Serilog. You log stuff, right?
  • the singleton is public with a public getter because WPF bindings only work on public properties. The internal setter doesn't affect it. All the properties of Settings are public for WPF binding.

I left all the "noise" in the code because some may find it useful.

class Settings : INotifyPropertyChanged
{
    private static Settings _currentSettings = new Settings();

    /// <summary> The one and only Current Settings that is the current Project. </summary>
    [JsonIgnore] // so it isn't serialized by JSON.NET
    public static Settings CurrentSettings //  http://csharpindepth.com/Articles/General/Singleton.aspx 
    {
        get { return _currentSettings; }

        // setter is to load new settings into the current settings (using JSON.NET). Hey, it works. Probably not thread-safe.
        internal set 
        {
            Log.Verbose("CurrentSettings was reset. Project Name: {projectName}", value.ProjectName);
            _currentSettings = value;
            _currentSettings.IsChanged = false;
            NotifyStaticPropertyChanged("CurrentSettings");
        }
    }

    // http://10rem.net/blog/2011/11/29/wpf-45-binding-and-change-notification-for-static-properties
    /// <summary> Fires when the Curent CurrentTvCadSettings is loaded with new settings
    ///           Event queue for all listeners interested in StaticPropertyChanged events. </summary>
    public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged = delegate { };
    private static void NotifyStaticPropertyChanged(string propertyName)
    {
        StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
    }

    // various instance properties including ....

    public string ProjectName {get; set;}

    [JsonIgnore]
    public bool IsChanged { get; set; } 
}

usage to set the singleton to a newly loaded project, settings is simply

Settings settings = new Settings();
// load, save, deserialize, set properties, go nuts
Settings.CurrentSettings = settings;

The setter probably isn't thread-safe but I only set it in one place from the UI thread so I'm not scared. You could make it thread safe following the esteemed advice at http://csharpindepth.com/Articles/General/Singleton.aspx

I realise the OP didn't ask about WPF but I think it's relevant to show why you may want to set a singleton. I did it because it is the simplest solution.

CAD bloke
  • 8,578
  • 7
  • 65
  • 114
0

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#

Philm
  • 3,448
  • 1
  • 29
  • 28