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#
- Static provide an easy way to call methods and fields.
- Method which doesn’t work differently for different objects can be used as static.
- App configuration class can be a good example for static class/methods. Because it stays same throughout the application.
- Database Connection string is another good use case of static method.
- Static members make code cleaner.
- Mainly utility kind operations should be mark as static.
When not to use static in C#
- Static hinders unit testing.
- Static missing OOP concepts including abstractions.
- Do not use static when the class or field is going to change according to caller class.
- Async or multithreading sometimes conflicts with static, mostly if someone mark data access layer as static(which is not recommended)