Hi All, 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 simply denotes that you don't expect or need an instance. This is useful for utility logic, where the code is not object-specific. For example, extension methods can only be written in a static class.
Pre C# 2.0, you could just have a regular class with a private constructor; but static
makes it formal the you can never have an instance (there is no constructor*, and all members must be static).
(*=see comment chain; you can optionally have a type initializer (static constructor aka .cctor
), but you cannot have an instance constructor (aka .ctor
)).
All members of a static class has to be static members, so, if you forget to add 'static' before any of them your code won't compile, it also makes your code more readable as anyone who will see that the class is static will understand it only contains static members.
The best use for a static class is for utility functions, you could also use them to keep the global methods and data in your application, I use static static classes very often in almost any project.
Static classes are sealed. This may be a useful option to use static for utility classes.
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.
Static classes are often used to group related global services which you initially don't want to be accessed with an object instance. An example is the Math class in the .Net BCL, which you use directly, e.g., Math.Sqrt(10.0)
A static class is a language hack to write procedural programs in C#.