Why we cannot create the Instance of the Static Class in .Net

22,482

Solution 1

Static classes do not contain any instance member properties or functions. So to make an instance would be pointless.

Static classes are used for containing Variables, properties and functions that have the same effect all over your program.

For example you can have a "Settings" class.

That has all static properties.

When it is accessed (via static constructor) Automatically loads the settings file from disk or resets to default settings if the file is not found.

now from all over your program you can access this class by just calling

  • Settings.ScreenSize
  • Settings.RootPath

You can even create a function

  • Settings.Save() to save the settings to disk for next use.
  • Settings.Reset() to restore the default settings.

The advantage of this is that all your settings will be grouped in one place and all logic for your settings is placed in one spot. You will always know that there is only one instance of the settings class from wherever you call it

I hope this helps

Solution 2

When we make class as static, Compiler gives guaranty that instance of this class (Static class) can not be created. therefore the methods are not associated with particular object of class in code.

Static class can not contains instance constructor But it can contain static constructor which does not takes the access modifiers. Static constructors is called automatically to initialize the class before the first instance is created.

Static class are sealed classes and therefore can not be inherited.

You can access the static members using the type name instead of reference.

Share:
22,482
Bhupendra Shukla
Author by

Bhupendra Shukla

Updated on July 01, 2020

Comments

  • Bhupendra Shukla
    Bhupendra Shukla almost 4 years

    According to the MSDN

    "A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language run-time (CLR) when the program or namespace containing the class is loaded."

    After doing some research on it, I find that static classes does not contains the instance constructor. I do not understand why static classes does not contains the instance constructor and what is the use of the static keyword. Why .Net does not allow us to create the instance of a static class?