DEV Community

Cover image for When to use static and when not to in C#

Posted on

When to use static and when not to in C#

In the last post I talked about static keyword. Today I will write about the usage of static. I recommend first read that article where you can get a brief idea about static before read this article.

When to use static in C#

  1. Static provide an easy way to call methods and fields.
  2. Method which doesn’t work differently for different objects can be used as static.
  3. App configuration class can be a good example for static class/methods. Because it stays same throughout the application.
  4. Database Connection string is another good use case of static method.
  5. Static members make code cleaner.
  6. Mainly utility kind operations should be mark as static.

When not to use static in C#

  1. Static hinders unit testing.
  2. Static missing OOP concepts including abstractions.
  3. Do not use static when the class or field is going to change according to caller class.
  4. Async or multithreading sometimes conflicts with static, mostly if someone mark data access layer as static(which is not recommended)

Top comments (2)

davidkroell profile image
David Kröll

I personally never use static except for extension methods. In my opinion it just makes the code less concise. It is also bad for maintainability. The performance point of view is also no good argument to me, because the impact is so small.

I typically use DI for every use-case, so static is barely required (except extension methods).

shariaretanvir profile image

Yes. Singleton class are good for those kind of scenario.