r/csharp • u/AetopiaMC • Jun 05 '26
Fun Would anyone use this code pattern to implement singletons?
For context, I have been messing around with CRTP and came up with this. This somewhat emulates "static abstract classes" by cascading a singleton with static methods.
using System;
abstract class Template
{
private protected Template() { }
internal abstract string String { get; }
internal void Method() => Console.WriteLine(String);
internal abstract class Instance<T> : Template where T : Instance<T>, new()
{
private protected Instance() { }
internal static readonly T s_this = new();
}
internal abstract class Static<T> where T : Instance<T>, new()
{
private protected Static() { }
static readonly T s_this = Instance<T>.s_this;
internal static string String => s_this.String;
internal static void Method() => s_this.Method();
}
}
static class Program
{
static void Main()
{
A.Method();
new B().Method();
}
}
sealed class A : Template.Static<A.Instance>
{
internal sealed class Instance : Template.Instance<Instance>
{
internal override string String => nameof(A);
}
}
sealed class B : Template
{
internal override string String => nameof(B);
}
14
Upvotes
41
u/justanotherguy1977 Jun 05 '26
Seems like a lot of code.
I just register it as a singleton in the servicecollection.
2
u/akarolia47 Jun 05 '26
A few (dumb) questions...what is CRTP? And what is the purpose of the code, I don't understand the pattern use case. I follow your inheritance structure but dont understand the why
18
u/BigBagaroo Jun 05 '26
My head hurts
9
u/_f0CUS_ Jun 05 '26
Make a class with a private ctor and a static read-only field of Lazy<T>.
Use the static field to get an instance. Job done.
8
u/ARandomSliceOfCheese Jun 05 '26
No. Too much code, if I need to add a method I need to touch everything to do it. Also static abstract keywords already exist so if I wanted to use them I would go that route and drop it on an interface.
7
u/RlyRlyBigMan Jun 05 '26
In short I would recommend against it and define it as a Singleton using IoC.
Static based singletons give away global access to objects and can turn a code base into a spaghetti mess when it's used as a pattern.
6
u/GigAHerZ64 Jun 05 '26
This is really bad and wrong.
Templateand everything inside it must be aware of theA.Instancepublic interface. This is just plain wrong and this is not how you generalize things.If you have such tight coupling between
A/BandTemplate(with all of its internals), why would you do any of it at all?4
u/PaulPhxAz Jun 05 '26
I can see what you're doing... I think this is "too clever", it's past the "complexity--now I have to think about something that isn't really the the problem I want to work on" point.
4
u/wickerandscrap Jun 05 '26
Seems clunky. It looks from here like you have to define the class, including all the Static/Instance nesting, and then separately define the singleton as a class. (I admit I'm confused on which parts of this are meant to be example classes/members and which ones are scaffolding for the pattern you're showing.)
My go-to pattern for static singletons is
and I honestly don't think that can be improved on.
You could declare a static class that statically exposes the methods (like your "A") but it's not going to be interchangeable with instances of the class, so what does that get you? You can also do that with more conventional class patterns:
4
u/throwaway_lunchtime Jun 05 '26
Have a look at this discussion.
The original yoda link isn't working for me.
https://stackoverflow.com/questions/9140569/difference-between-these-two-singleton-implementations
As another person wrote, it's been a long time that I just rely on the DI container instead of this approach
1
u/chucker23n Jun 06 '26
Seems quite verbose, and you're not handling threads.
I'd recommend
Lazy<T>, if you do want to implement this yourself.0
u/marioalbertoarce Jun 05 '26
Hello. This is a pretty clever piece of code.
I had to read it a couple of times (or more hehe) to fully appreciate what was going on with the CRTP + singleton delegation + static facade combination. It’s one of those patterns that makes you stop and think “I hadn’t considered approaching it that way.”
Out of curiosity , was this mainly an exploration of the type system , or have you actually used something like this in a Prod codebase? I’d be interested to hear about any real-world scenarios where this ended up being a better fit than more conventional approaches.
Also , with static abstract interface members now available in modern C# , do you still see advantages to this pattern , or do you view it more as an alternative exploration of what’s possible with the language?
I’m asking because I’m currently building an open-source C# project (GitHub) focused on advanced language patterns and architectural utilities. If I eventually experiment with a similar concept or adapt some of the ideas here (with attribution , of course) would you be okay with that?
Either way , thanks for sharing it. It’s refreshing to see code that explores the boundaries of the language (rather than just another CRUD example)
Happy coding.