What is the use of a static class? I mean what are benefits of using static class and how CLR deals with static classes?
A static class is a language hack to write procedural programs in C#.
The compilation and metadata model for .net requires that all functions are defined within a class. This makes life somewhat easier and simpler for the reflection api's since the concepts of the owning class and its visibility is well defined. It also makes the il model simpler.
since this precludes free functions (ones not associated with a class) this makes the choice of where to put functions which have no associated state (and thus need for an instance). If they need no state associated with them nor have any clear instance based class to which they can be associated and thus defined within there needs to be some idiom for their definition.
Previously the best way was to define the methods within a class whose constructor was private and have none of the functions within the class construct it.
This is a little messy (since it doesn't make it crystal clear why it was done without comments) and the reflection api can still find the constructor and invoke it.
Thus static classes were allowed, making the intent of the class, that of a place for the definition of static methods, clear to users and to the type system. Static classes have no constructor at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With