Tech Point Fundamentals

Saturday, October 3, 2020

Static Class, Constructor and Method in C#

Static Class, Static Constructor, and Static Method in C# with Real Time Examples

StaticClass-StaticConstructor-StaticMethod

  Static means something which cannot be instantiated. Typically, a static class is the same as a normal class except that a static class cannot be instantiated and inherited. A static member cannot be accessed by the class object. A static class, static constructor, and static method or member are the most common topics for the interview nowadays. In this article, we will walk through static classes, constructors, and methods in detail with real examples.


Please visit our Youtube Channel to watch our videos by the below link:


Introduction

In C# classes, constructors, methods, variables, properties, events, and operators can be defined as static using the static modifier keyword. However, the interfacestructure, indexers, enum, and destructors or finalizers cannot be declared as static.


When you use the static keyword for the declaration of a field,  property, or method, then it is called a static member, and they are accessible directly by type name, without even creating the object.




Static Class

In C# static class is a special class that has features of both an abstract class and a sealed class, since an abstract class can not be instantiated and a sealed class can not be inherited. When a class is declared to be static, it is sealed and abstract by default. The concept of a static class was introduced in C# 2.


You can also say that creating a static class is the same as creating a normal class with all static members and having a private constructor since a private constructor prevents the class from both being instantiated and inherited.


A class declared with the static modifier is called a static class. A static modifier can only be used just before the class keyword and after the access modifier to make a class static. 

All the members of a static class are static in nature. A static class can only contain static data members, static methods, and a static constructor.



Static Class Features

    1. Static class members can only be accessed by the Class Name and not by any instance variable.
    2. The static class remains in memory for the lifetime of the Application Domain in which your program resides.
    3. Only one copy of a static member exists, regardless of how many instances of the class are created. 
    4. A static class is loaded by the CLR when the program that references the class is loaded. 
    5. A program cannot specify exactly when the static class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program.
    6. A static class can contain const field members but a const field cannot be declared static explicitly because a const field is static implicitly and it belongs to the type,  not to instances of the type.
    7. A static class can contain enums since it is sealed implicitly by default. An enum can be directly accessed by the class name itself.

Static Class Rules

    1. A static class cannot be instantiated like a normal class because static classes are abstract implicitly by default.
    2. A static class cannot be inherited since static classes are sealed implicitly by default.
    3. Any explicit sealed modifier is not allowed for a static class because the static class is sealed by default.
    4. A static class can only contain a parameterless static constructor but without any access modifiers.
    5. A static class can contain only static data members, except const and enum.
    6. Explicit destructor is not allowed in the static class.
    7. No indexers are allowed in a static class since an indexer cannot be static because this pointer is not allowed for referencing static members.
    8. A static class cannot inherit from any class except System.Object class. Since Object is the ultimate base class of all the .NET Classes; it is the root of the type hierarchy. Languages typically do not require a class to declare inheritance from Object because the inheritance is implicit.
    9. A static class cannot contain any instance members or instance constructors, since instantiation is not allowed.
    10. The contextual keyword "var" cannot be used to define any static members. You must have to specify a type of member explicitly after the static keyword.



Static Constructor

A constructor declared with the static modifier is known as a static constructor. A static constructor cannot contain any argument parameters. 


A static constructor is used to initialize the static data members or to perform a particular action that needs to be performed only once. Only a parameterless static constructor is allowed.






Static Constructor Features

    1. A static constructor is executed only once in the lifetime of the program or application. 
    2. The static constructor is called just before the first instance is created or any static member is referenced. 
    3. A static constructor always executes before the instance constructor
    4. If a static method is assigned to a delegate or event, then the static constructor is called only when a static method assigned to an event or a delegate is invoked and not when it is assigned. 
    5. A static class cannot contain any non-static constructor, but a non-static class or struct can contain a static constructor.
    6.  A static constructor cannot be called directly and is only meant to be called by the CLR. It is invoked automatically by the runtime.
    7.  The user has no control over when the static constructor is executed in the program.
    8. If you don't provide a static constructor to initialize static fields, all static fields are initialized to their default value.
    9. The presence of a static constructor in any class or struct prevents the addition of the BeforeFieldInit type attribute. BeforeFieldInit specifies that calling static methods of the type (class, struct) does not force the system to initialize the type (class, struct). This limits runtime optimization.
    10. If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running. Most commonly, a TypeInitializationException exception is thrown when a static constructor is unable to instantiate a type or for an unhandled exception occurring within a static constructor. 

Static Constructor Rules

    1. A parameterized static constructor is not allowed.
    2. No access modifier is allowed for static constructors since they are private implicitly. Since if a static constructor is not private implicitly, it can be called by code other than the system.
    3. Static constructor overloading is not allowed i.e. only one static constructor is allowed because a static constructor can only be parameterless.
    4. Only a class or struct can contain a static constructor. A structure cannot contain a parameterless constructor but a static constructor is allowed which is always parameterless.
    5. A static constructor cannot be inherited since it is private implicitly.
    6. A static constructor can only access or initialize static data members.



Use of Static Constructor 

    1. Static constructors are useful when creating wrapper classes for unmanaged code when the constructor can call the LoadLibrary method.
    2. A field declared as static readonly may only be assigned as a part of its declaration or in a static constructor. 
    3. Static constructors are also a convenient place to enforce run-time checks on the type parameter that cannot be checked at compile-time via constraints (Type parameter constraints).





Static Methods and Data Members

A method declared with the static modifier is known as a static method. A static method can only access static data members. 

All the members like properties, fields, events, methods, or operators that are declared with the static keyword are known as static data members.



Static Method Features

    1. A non-static class can also contain static methods and static data members
    2. A structure can also contain static methods and static data members, but a structure cannot be static itself.
    3. A static method can contain out and ref type parameters.
    4. With the introduction of C# 8, an interface can also contain static methods, but static instance variables are not allowed.
    5. Static data members and methods can only be accessed by the class name itself, they cannot be accessed by the object of the type.
    6. const field member cannot be declared as static explicitly, since a const field is implicitly static in its behavior. A const type belongs to the type, not to the instances of the type. 

Static Method Rules

    1. The static modifier can only be used just before the return type and after the access modifier.
    2. Static methods can be overloaded but cannot be overridden, since they belong to the class, and not to any instance of the class.
    3. A static method cannot contain any local static variable.
    4. Static methods cannot access any non-static variables unless they are explicitly passed as parameters. A static method can contain ref and out parameters.
    5. A static method can only be assessed by the type name itself, not by the type object. 
    6. A static method can only call other static methods and access static members.
    7. A static method cannot be marked as virtual, sealed, or abstract.

Example


 



If you check the
IL Code of the above program in ILDASM:

StaticClass-StaticConstructor-StaticMethod-ILCode


  1. IL code line ".class public abstract auto ansi sealed" proves that static class is abstract and sealed implicitly by default.
  2. IL code line ".class auto ansi sealed nested public ObjectType" proves that enum is sealed implicitly by default.
  3. IL code line ".field private static literal int32" for const type field variable "MeterToCentimeter" proves that a const type variable is static by default.
  4. IL code line ".method private hidebysig specialname rtspecialname static void  .cctor()" proves that static constructors are private by default. The attributes "specialname rtspecialname" are used by the CLI or CLR to determine if an attribute or method has a special use or significance.
  5. IL code line ".class public auto ansi beforefieldinit" for "Program" class (which has no static constructor at all) proves that the presence of a static constructor in any class or struct prevents the addition of the BeforeFieldInit type attribute.



Memory Management for Static Class and Members

In .Net,  CLR divides the system memory into three distinct regions called Stack, Heap, and High-Frequency Heap. Normally there is a High-Frequency Heap for each app domain and it is beyond the scope of GC hence this memory gets released only when the corresponding Process or App Domain gets unloaded.


We know that since static members can be accessed directly without creating instances of the class, they must exist in the memory throughout the lifetime of the application; they don’t need to be garbage collected. Therefore, static members are stored in a special memory area called High-Frequency Heap.


For each and every static data member, the memory will be allocated individually, without any relation to the object. If a class or any member is declared as static then, it is not collected by the Garbage Collector.


Static members of non-static classes or structs are shared across all the instances of the class or struct. So, the changes done by one instance will be reflected in all the other instances.




Use or Advantages of Static Class and Method

    1. Static classes and methods are used for creating Extension Methods.
    2. The static method is used in Singleton Implementation.
    3. The static method is used to implement a Factory Pattern.
    4. The static Main() method is used for the entry point of the Console Application and Windows Application.
    5. The main advantage of a static class is that it guarantees that only one global instance will be created by the CLR and no instantiation is allowed.
    6. A static class can be used to implement helper or utility classes as static classes don’t need to be instantiated or inherited and generally contain a collection of some reusable methods and properties.
    7. The most common uses of static fields are to keep a count of the number of objects that have been instantiated or to store a value that must be shared among all instances.
    8. Static methods are faster in execution than non-static methods since the runtime passes this pointer as an implicit parameter to the non-static methods. For a non-static method, the compiler generates the callvirt instruction even if the method is non-virtual, which also checks for null object references. When you make your methods as static, the compiler emits a non-virtual call and eliminates the extra check for whether the instance is null.



Disadvantages of Static Class and Methods

Static classes can be useful in certain situations, but there is a potential to abuse them. The most obvious case for using a static class is if you have a class with only static methods. 


    1. Since in OOPS, object behaviors are usually associated with object state i.e. the behavior should belong to the object. But by using a static function you are implying that the behavior shouldn't belong to any particular object.
    2. Polymorphic and interface-driven designs are also hindered by overusing static classes and methods since a static method cannot be overridden in the derived class and a static class cannot be attached to an interface. 
    3. One of the most common pillars of OOPS i.e. inheritance is also not supported by the static class. Since a static class can neither inherit from other classes nor be inherited by other classes.
    4. Also, a static class cannot contain any indexer.
    5. A structure can contain static members but cannot be static itself.
    6. No user or program control over static constructors.

 



Real Examples of Static Class and Method

Following are the most commonly used static classes and structures containing static methods available in .Net:


    1. System.Math is a static class  
    2. System.IO.File is a static class
    3. System.Environment is static class class
    4. System.String is a sealed class that contains static methods (like Format, Compare, Concat, Equals, Join )
    5. System.TimeZone is an abstract class that contains CurrentTimeZone and IsDaylightSavingTime static methods.
    6. System.DateTime is a structure that contains a lot of static methods and operators (like Now, UtcNow, Today, Parse, Equals)
    7. System.Int16, System.Int32 and System.Int64 are structures that contain Parse, TryParse static methods.
    8. System.Double and System.Single are structures that contain a lot of static methods and operators (like Parse, TryParse, IsInfinity, IsNaN, IsNegativeInfinity, IsPositiveInfinity, operator ==, !=, <,>,<=,>=)
    9. System.Boolean is a structure that contains Parse and TryParse static methods.



Static Class Vs Instance Class

    1. A static class cannot be instantiated while you are allowed to create objects of a non-static class by using a new keyword.
    2. All the data members of a static class can only be accessed by its class name, while the non-static data members of the non-static class cannot be directly accessed by its class name.
    3. A static class can only contain static members, while a non-static class may contain both static and non-static members.
    4. A static class can only contain a static constructor, while a non-static class contains both static and instance constructors.
    5. A static class cannot inherit from another class while a non-static class can inherit from another class.
    6. A static class cannot be inherited by any class while a non-static class can be inherited by other classes.
    7. A static class cannot implement any interface while a non-static class can implement the interface.
    8. A static class cannot contain indexers while a non-static class can contain indexers.



Live Example



Conclusion

A static class can only contain static members and can not be inherited or instantiated.  A static constructor can not contain any parameter. A static method can only call or access other static methods or static members. A non-static static class and struct can also contain static constructors and static members.


Recommended Articles


Abstract Class Vs Interface
Partial Methods in C#
Partial Types and Partial Classes in C#
Partial Interface Methods in C# 8
Interface Member Modifiers in C# 8
Multiple Interface Inheritance in C# 8
Interface Virtual Method in C# 8
Interface Access Modifiers in C# 8


Thanks for visiting this page. Please follow us on Twitter, Facebook, LinkedIn, Youtube, Quora, and Pinterest for regular updates.




Video Recommendation

Watch More Videos...

4 comments:

  1. Too Good Article!! all .NET and C# is covered in one place. Anyone preparing for interview, best place to brush up basics. Kudos!!

    ReplyDelete
    Replies
    1. Thank you very much Sharmila!

      You can visit my Youtube channel for more interview questions and answers videos: https://www.youtube.com/c/TechPointFundamentals?sub_confirmation=1

      Delete
  2. Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though. Satta king result

    ReplyDelete
  3. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.. Patco Construction

    ReplyDelete

Please do not enter any HTML. JavaScript or spam link in the comment box.