Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static classes pros and cons [duplicate]

I am a C++ programmer who makes a switch to C#.I was said not to use static classes. I understand that in C# if the class has only static members it should be static.(My class has only static members) Can you please explain me what could be a problem using static classes? When we really should use them?

Thanks

like image 277
Yakov Avatar asked Oct 20 '22 14:10

Yakov


2 Answers

The main reason is that sometimes (but NOT always), it's better to use a singleton class, because a singleton class can implement interfaces.

like image 200
Eliran Pe'er Avatar answered Nov 03 '22 23:11

Eliran Pe'er


Static classes have no difference from non-static classes apart from the fact that you can't instantiate static classes (because they're static of course) and this static class will not be able to take advantage of cool OOP features such as inheritance (it can't be subclassed in C#).

The main thing you have to be aware of when a static class contains static members is making the class static members thread-safe if used by multiple threads.

Can you please explain me what could be a problem using static classes? When we really should use them?

If your class only exposes static members then you can make it a static class, but only if you are sure you will not need instances of this class. In fact, there's absolutely no issues in using static classes, just make then thread-safe (if required) and make sure it fits in with your system's design.

like image 25
Leo Avatar answered Nov 04 '22 00:11

Leo