Why are static classes used?

喜夏-厌秋 提交于 2019-12-01 16:12:07

For utility classes they are great. As you mentioned, they are similiar to global state. So for classes which have no state, for performance benefits the class should be static.

On the other hand, static classes are hard to test (if they contain state). Polymorphism and other OO concepts are also lost.

Use wisely.

Hans Passant

Applying the static keyword to a class is a C# language convention, it doesn't mean anything special to the CLR. It merely makes sure that all members are static as well and that you can't accidentally create an instance of the class with the new keyword.

The merits of static methods are discussed in this thread.

IMO static classes are procedural programming in disguise. Not necessarily a bad thing, but it's not very OOPly. Watch out for the functional decomposition antipattern.

Static classes are great for defining static methods. This is classic 'utility class' approach. However, be extremely careful with storing state (i.e. defining fields) in a static class. In our multi-threaded world this can lead to unpredictable program behavior unless you synchronize access to static fields.

Static properties mainly used to introduce Context of running code. And you can find confirmation for that in every piece of .NET stack.
ASP.NET - HttpContext.Current
Threading - Thread.CurrentThread
WinForms - WindowsFormsSynchronizationContext.Current
WPF - Dispatcher
etc
static class for me is just container for utility methods.

Static Classes globalizes a particular variable which makes it easier to handle during the code. Hence at basic level we prefer using Static Classes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!