Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of a static class

Tags:

c#

.net

What is the use of a static class? I mean what are benefits of using static class and how CLR deals with static classes?

like image 721
Embedd_0913 Avatar asked Feb 23 '09 08:02

Embedd_0913


2 Answers

A static class is a language hack to write procedural programs in C#.

like image 178
Chris Peterson Avatar answered Oct 21 '22 21:10

Chris Peterson


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.

like image 40
ShuggyCoUk Avatar answered Oct 21 '22 21:10

ShuggyCoUk