C# Static Class

In C# programming language, a static class resembles a regular class in structure, with the key difference being that it cannot be instantiated or inherited. This type of class is limited to static members like methods, fields, properties, and constructors. Being inherently sealed and abstract, a static class is ideal for encapsulating utility or helper functionalities that do not necessitate object instances.

The CSS code snippet below illustrates the styling for a placeholder diagram in a web design project:

Example

.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }

The Common Language Runtime (CLR) ensures that the static members of a class are loaded and accessible throughout the application's lifespan.

Syntax:

It has the following syntax:

Example

static class ClassName

{

    // static fields

    // static properties

    // static methods

}

In this format,

  • ClassName: It denotes the title of the class.
  • static class ClassName: It signifies the static class type.
  • Static Class Example in C#

Let's consider an instance to demonstrate the static class that encompasses a static field and a static function in C#.

Example

Example

using System;  

   public static class MyMath  

    {  

        public static float PI=3.14f;   

        public static int cube(int n){return n*n*n;}  

    }  

   class TestMyMath{  

       public static void Main(string[] args)  

        {  

            Console.WriteLine("Value of PI is: "+MyMath.PI);  

            Console.WriteLine("Cube of 3 is: " + MyMath.cube(3));  

        }  

    }

Output:

Output

Value of PI is: 3.14

Cube of 3 is: 27

Explanation

In this illustration, we define a fixed class named MyMath containing a constant field PI and a static function cube which calculates the cube of a number. Within the Main function of TestMyMath, both elements are directly utilized via the class identifier without the need for creating an instance. Subsequently, it displays the PI value and the cube of 3.

Points to remember for C# static class

Several important points for static class in C# are as follows:

  • A C# static class contains only static members.
  • A C# static class cannot be instantiated.
  • A C# static class is sealed.
  • A C# static class cannot contain instance constructors.
  • Static class members can be accessed u the class name.
  • Static classes can be created once and remain for the lifetime of the application.
  • When to Use Static Classes in C#?

In C#, static classes serve a valuable purpose in consolidating methods, properties, or fields. They are globally accessible within the application and do not rely on instances. Static classes are ideal for utility tasks like managing configurations, executing mathematical calculations, logging data, or manipulating strings. They are particularly beneficial for functionalities that are consistent and stateless.

Static classes prevent instantiation or inheritance, guaranteeing a unified and globally accessible set of members. They are ideal for scenarios requiring a sole instance of data or logic throughout the program's execution.

C# Static Class Example for Application Configuration

Let's consider another instance to demonstrate the static class used for application settings in C#.

Example

Example

using System;

public static class AppConfig

{

    public static string AppName = "MyCoolApp";

    public static string Version = "1.0.0";

    public static bool IsDebugMode = true;

    public static void ShowConfig()

    {

        Console.WriteLine("App Name: " + AppName);

        Console.WriteLine("Version: " + Version);

        Console.WriteLine("Debug Mode: " + (IsDebugMode ? "ON" : "OFF"));

    }

}

class Program

{

    static void Main()

    {

        AppConfig.ShowConfig();

        AppConfig.IsDebugMode = false;

        Console.WriteLine("\n-- After Updating Debug Mode --\n");

        AppConfig.ShowConfig();

    }

}

Output:

Output

App Name: MyCoolApp

Version: 1.0.0

Debug Mode: ON

-- After Updating Debug Mode --

App Name: MyCoolApp

Version: 1.0.0

Debug Mode: OFF

Explanation:

In this instance, we're examining the AppConfig class defined as a static class, indicating it's not possible to create instances or derive from it. Instead, its properties are accessed directly by referencing the class name. This class is designed to hold universal configuration settings like AppName, Version, and IsDebugMode. To showcase these values, the ShowConfig function is employed, ensuring any modifications to the static fields are immediately apparent throughout the program.

Difference between Static Class and Non-Static Class

There exist numerous distinctions between a static class and a non-static class in C#. Here are some key variances:

Static Class Non-Static Class
The static keyword declares a static class. The static keyword does not declare a non-static class.
The members of a static class can be accessed directly by its class name. The members of a non-static class are not accessed directly by its class name.
A static class cannot be inherited from another class. A non-static class can be inherited from another class.
A static class has no instance constructor. A non-static class has an instance constructor.
A static class always holds static members. A non-static class can hold both static and non-static methods.

Advantages of Static Class

Several advantages of Static Class in C# are as follows:

  • Global Accessibility: We can access the static classes directly using the class name, which can help to make them effective and reliable during the program without creating objects of the classes.
  • One-Time Initialization: If we initialize static fields and data only once, it ensures the reliability across the entire program.
  • Improved Performance: As static members remain the same in the memory for the entire program, there is no need to create repeated objects or garbage collection overhead, which helps to improve the performance of the program.
  • Thread Safety with CLR Initialization: The .NET Framework runtime makes sure that static constructors and initializations are controlled in a thread-safe manner.
  • Disadvantages of Static Class

Several disadvantages of a Static Class in C# are as follows:

  • No Inheritance: Static classes cannot be inherited in the program, which can restrict the code flexibility and reusability.
  • Memory Usage: Static members will stay unchanged in the memory during the program's lifetime, which can help to increase the memory consumption if they hold a large amount of data.
  • Tight Coupling: The utilization of static classes for a long time can increase the coupling between different code segments, which can make it harder to test or refactor.
  • No Instantiation: Static classes cannot be instantiated in the program, which means we cannot create any object to store different states of the program.
  • Conclusion

In summary, a static class in C# is a class type that can gather methods, properties, or constants without needing an object instance. It offers a unified or shared definition across the application, making it ideal for utility functions, configuration settings, or helper logic. Due to its inability to be inherited or instantiated, it allows for enhanced control, memory efficiency, and convenient access through the class name. When utilized correctly, static classes can promote cleaner and well-structured code.

Static Class FAQs

1) What is a static class in C#?

In C# programming, a static class is one that cannot be instantiated and contains only static members. It is defined with the static keyword and does not allow instance constructors. Static classes are commonly employed to house utility functions or helper methods for universal accessibility.

2) Can a static class have constructors?

Yes, only a static constructor is available for initializing static members. This constructor doesn't take any parameters and is automatically triggered once before accessing any member. The timing of its invocation is beyond your control, and it cannot receive any parameters.

No, a static class cannot be derived from another class or inherited.

No, static classes are sealed and incapable of being derived or inherited. They implicitly inherit from the object, similar to all other classes.

4) Where is a static class located in memory?

In the application domain's memory, the information is typically loaded once during the entire application's lifespan. The data is stored in the memory section designated for static members, often found in the heap area. The Common Language Runtime (CLR) ensures that static constructors are initialized in a thread-safe manner.

Yes, it is possible to include static methods within a non-static class.

Yes, it is possible to define static methods in both static and non-static classes. Static methods belong to the class itself rather than any specific object instance, allowing them to interact directly with other static class members.

Input Required

This code uses input(). Please provide values below: