Static Classes and Static Class Members in Microsoft.NET


Static Classes and Static Class Members

  

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class.

The data and functions do not change regardless of what happens to the object.

Static Classes

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 runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object.

The main features of a static class are:

They only contain static members.

They cannot be instantiated.

They are sealed.

They cannot contain Instance Constructors.

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.

Static Members

A static method, field, property, or event is callable on a class even when no instance of the class has been created.

If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.

Static class members are declared using the static keyword before the return type of the member.

Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member.

 

Advertisements

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s