5

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

YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • There's nothing at all wrong with `static` classes when used appropriately. You need to be careful about *static state* (i.e. `static` fields) - for both data isolation and multi-threading reasons . So it depends a lot on what you are doing ;p – Marc Gravell Feb 20 '14 at 08:33

3 Answers3

2

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

Eliran Pe'er
  • 2,569
  • 3
  • 22
  • 33
1

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.

Leo
  • 14,625
  • 2
  • 37
  • 55
0

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated.

http://msdn.microsoft.com/en-us/library/79b3xss3.aspx

Check also this link:

When to use static classes in C#

Community
  • 1
  • 1
Rami
  • 7,162
  • 1
  • 22
  • 19