static keyword in C#

When a class member is prefixed by a static keyword, it becomes a static member, and it must be invoked directly from the class level, rather than from an object reference variable. Static members promote a given item to the class level rather than the object level. Static data is allocated once and shared among all instances of the class. The CLR allocates the static data into memory exactly one time.

While any class can define static members, they are quite commonly found within utility classes. By definition, a utility class is a class that only exposes static functionality. It does not maintain any object-level state and is not created with the new keyword.
Rather, a utility class exposes all functionality as class-level (a.k.a., static) members.

The static keyword can be applied to data members, methods, properties, constructor, and entire class definition.

Note: this keyword cannot be used with a static member because this implies an object. A static member cannot reference non-static members in its implementation (it will generate a compiler error).

Q: What will happen if you attempt to assign the value of a static data member in a typical (non-static or instance level) constructor?

A: The the value of the static data member will be reset each time you create a new object.

Static Constructor: A static constructor is a special constructor that is an ideal place to initialize the values of static data when the value is not known at compile time (e.g., read in the value from an external file, a database, generate a random number, etc).

A static constructor allows us to initialize static members of a class at runtime. The CLR calls all static constructors before first use (and never calls them again for that instance of the application).

Few interesting points regarding static constructors:
  1. A given class can define only one static constructor. The static constructor cannot be overloaded.
  2. A static constructor does not take an access modifier and cannot take any parameters.
  3. A static constructor executes exactly one time, regardless of how many objects of the type are created.
  4. The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller.
  5. A static constructor cannot be called directly through the code.
  6. The static constructor executes before any instance-level constructors.
Static Class: A static class cannot be created using the new keyword (i.e; it cannot have an instance or object). It can contain only static members (static data members, static methods, static properties or a static constructor).

No comments:

Post a Comment