BrandGhost

I Pick *NEITHER* - Static Class Or Singleton In C#?

When faced with choosing between a static class or a singleton design pattern in CSharp, which way is the right way? Well, what if we didn't have to pick between these two options? Can we do something better than a singleton in C# or a static class? Have you subscribed to my weekly newsletter yet? A 5-minute read every weekend, right to your inbox, so you can start your weekend learning off strong: https://subscribe.devleader.ca Check out more Dev Leader content (including full in-depth articl...
View Transcript
all right should you be using a static class or a Singleton well I think maybe the answer is neither and in this video I wanted to go over a question from a Reddit thread that I thought was pretty interesting and I think that it's worth discussing because I don't think the answer is quite as black and white as it's made out to be before I jump over to Reddit for us to review this just a quick reminder to check that pin comment for a link to my free Weekly Newsletter and my courses on dome train but that said let's go check out this thread and see what's up all right so the original poster here says I have a class that connects to a database I only ever want a single instance of that class there will never be a need for this application to grow what is the best way to do this and then they kind of call out two situations that they're trying to pull from and it says my understanding of object-oriented programming is to make it instable intuition is telling me that it should be a static class so they're kind of going between either just a Singleton or a static class now I have a response to this that I wrote and I tried to keep it on track with what the op is asking for which is really static class or Singleton but I do think that it's a little bit more involved than that and if I had to give them my answer that was outside of that it would be neither now before I go into that I wanted to highlight this part in particular that says there will never be a need for this application to grow and some of the responses on this thread are people going well you know how can you say that that's kind of dangerous it's like you know close-minded but I think that it's important to look at this because we don't really have a lot of context for what this person's doing so this could be over engineering if people are like hey look like you're going to want a design to scale this up and you know future proof it like maybe I mean if I were doing this in a production environment I probably would want to be thinking about that but if this is just a hobby project for this person to play around with and they're like look I just need this up and running and it's got some constraints and limitations I just need it to work like this is probably okay to pick between either static or a Singleton but if I had to pick between the two I do have a preference so I'll share that and then I'll explain why I would probably pick neither given a little bit more flexibility so I have my response on the screen and basically what I was trying to get at is that I probably wouldn't use a static class and I'm someone that's pretty adverse to using static classes in the first place but with a static class and mixing in state which is what you're going to have if you have a database connection I think this is usually a recipe for a lot of bugs one of the dangers with static classes is that you have access to it from basically anywhere in your application and that means if there's State and anyone can access or play around with that state you might get some undesired Behavior because you can't really control who's accessing it depending on how complicated your app is you might be in situations where people are manipulating that state changing it and other people are reading it at unexpected times and you just get Behavior that's not really in your control so more often than not I will say like static classes in general not a huge fan of but a static class that really just has like read only information that's not changing like that's not so bad in my opinion now what I would do out of the two options is use a Singleton so if you had to pick between static or Singleton I would go with the Singleton personally and the Singleton gets a lot of flack right because it's like it's a little bit dangerous to use for the same reasons that a static classes but I think that the intent of a Singleton like the general purpose when we look at that design pattern it's supposed to be that you're enforcing only a single instance allowed to be created but what usually happens as a side effect is that we get Global accessibility to that instance as well I think by definition the global accessibility part does not need to be a requirement but I think the way that this gets implemented is that it's almost always a side effect of a Singleton and that's because if you're anywhere in your application and you tried to make a new instance of this you need to be able to prevent it so it's almost like from anywhere in the app application you need to ensure that you can't create a new one but the only way that you can kind of enforce that is if you have Global Information about that state so I don't think that's the intent with the Singleton but I do think it's a side effect generally and because that's the general side effect it kind of puts you in this same position as a static class which is why I don't really like either of these but I would go with the Singleton just because when it comes to refactoring things later if you needed to that moving away from the static class to a Singleton and then from a Singleton to something like Constructor parameter passing I think works a little bit nicer you start to have a little bit more control when you have a Singleton and you can enforce where people are accessing it from if you start passing it around instead of just having this static class that you can access from anywhere so as soon as you start to have an instance that can be moved around I think that's where you start to get into some access control that you have some flexibility over at least so what I recommended to this person is basically if you're picking between just those two things I would go with a single Singleton and then I said really the thing that I want you to be careful about is this idea that you can access this from anywhere so try to make sure that you're controlling and being careful about where that state is managed okay but what would I do instead of just using static or a Singleton well generally what I would do is try to think about our dependency injection framework so we have access to and you don't need a dependency injection framework for this but some of the concepts really are applicable here so with a lot of the DI Frameworks we use we can say that we want to create something and really just make one instance of it it doesn't enforce that no one else can make an instance of it it just means that when we are using a DI framework then only one thing will get created and that's probably what I would recommend to this person here even if they're not using a DI framework is you have full control over it you're saying that it's not really going to grow in complexity just make an instance of the thing make one instance and pass it around you don't need the Singleton design pattern to be able to enforce that single creation because if it's really that simple you just make one instance of it right at the top and that way you can move away from the static and have the global accessibility you can move away from the generic Singleton type of implementation that also has that Global accessibility you create your single instance and you start passing in through the Constructor if you want to use a DI framework even easier you still use Constructor parameter passing but your di framework can basically help enforce that single instance creation Now with this question we don't have a lot of context into the state of the application so for example example maybe this person started using static already I've worked in situations where I've had static classes scattered everywhere with state that was shared and pretty messy and what I ended up doing was refactoring the code slowly to start using a Singleton reference what was nice about having that Singleton reference is that over time again I could start passing that in through the Constructor which meant that I had some places that were going away with static other places getting the Singleton instance introduced in in favor of that static and then other places where the Singleton was going away because I was able to start passing in the reference through the Constructor and at the top level it was still that Singleton reference which is kind of interesting because all that I was doing was slowly chipping away at being able to pass it in through the Constructor and over time this was a refactor that took you know a very long period of time but by the end of it I ended up having a Singleton that was called in one spot right and then it gets passed into the construct and then pass down so on and so forth and at that point I could just switch it over to get rid of the Singleton entirely and just use dependency injection and basically create a single instance have it automatically resolved and the Singleton and the static are completely gone at that point if you're interested in seeing what a refactoring like that looks like you can check out this video next thanks and I'll see you next time

Frequently Asked Questions

What should I choose between a static class and a Singleton in C#?

If I had to choose between a static class and a Singleton, I would personally go with the Singleton. While both have their drawbacks, the Singleton allows for more control over instance management and can be refactored more easily later on.

Why do you recommend against using static classes?

I'm generally not a fan of static classes because they can lead to unexpected behavior due to global accessibility. When state is mixed with static classes, it can create bugs since any part of the application can access and modify that state.

What alternative do you suggest instead of using a static class or Singleton?

I recommend considering dependency injection. Even if you're not using a DI framework, you can create a single instance of your class and pass it around through the constructor. This way, you avoid the issues associated with static classes and Singletons while maintaining control over your instance.

These FAQs were generated by AI from the video transcript.
An error has occurred. This application may no longer respond until reloaded. Reload