This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Static Class


In this article we are going to discuss the Static class in C#. There are many blogs, articles are available on the internet regarding Static class but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the Static class in C#.

Static Class Introduction

  1. A static class is created using the static keyword in C# and .NET.
  2. C# static class contains only static members.
  3. C# static class cannot be instantiated.
  4. C# static class is sealed. Means you cannot inherit a static class from another class.
  5. C# static class cannot contain instance constructors.

Key Points to Remember for a Technical Interview

  1. Static classes cannot be instantiated or extended.
  2. A static class can only contain static members.
  3. Static members are accessed via the class name, not an instance of the class.
  4. Static classes are sealed and therefore cannot be inherited.
  5. Static constructors are called automatically when a static member is referenced.
  6. Static members are initialized only once, at the class loading.
  7. The 'this' keyword is not available in static methods since they belong to the class, not an instance of the class.

The following class definition defines a Static class in C#:

//Static class
static class classname
{
   //static data members
   //static methods
}

Types of Static Members in Static Class

In C#, the static class contains two types of static members as follows.

1. Static Data Members - As static class always contains static data members, so static data members are declared using static keyword and they are directly accessed by using the class name. The memory of static data members is allocating individually without any relation with the object.

Syntax

static class Class_name 
{
   public static nameofdatamember;
}

2. Static Methods - As static class always contains static methods, so static methods are declared using static keyword. These methods only access static data members, they can not access non-static data members.

Syntax

static class Class_name {
     public static nameofmethod()
     {
       // code 
     }
}

Real World Example of Static Class

Consider the static class System.math in the .NET framework; it consists of methods required to perform mathematical operations without any need to create the instance of math class.In this example, Math.PI, Math.Pow, Math.Max, and Math.Sqrt are all static members of the System.Math class. They are called directly on the class itself rather than on an instance of the class. This is a typical use case for static classes in the real world.

using System;

class Program
{
    static void Main()
    {
        // Using the static Math class to perform calculations
        
        double radius = 10.0;
        
        // Calculate the circumference of a circle
        double circumference = 2 * Math.PI * radius;
        Console.WriteLine("Circumference: {circumference}");
        
        // Calculate the area of a circle
        double area = Math.PI * Math.Pow(radius, 2);
        Console.WriteLine($"Area: {area}");
        
        // Using Math.Max to find the maximum of two values
        int a = 5, b = 10;
        int max = Math.Max(a, b);
        Console.WriteLine("Maximum: {max}");
        
        // Using Math.Sqrt to find the square root
        double number = 16.0;
        double squareRoot = Math.Sqrt(number);
        Console.WriteLine("Square Root: {squareRoot}");
    }
}

Example

let us understand static Class with an example. First, create a console application and then add a class file with the name Student.cs. Once you add the static class Student and add the following code.

namespace StaticConstructorsDemo
{
    class MyCollege
    {
        //static fields
        public static string CollegeName;
        public static string Address;

        //static constructor
        static MyCollege()
        {
            CollegeName = "BSA College of Technology";
            Address = "Mathura";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(MyCollege.CollegeName);
            Console.WriteLine(MyCollege.Address);
            Console.Read();
        }
    }
}

Output

Object

Memory Allocation for Static Items

You must be knowing that the basic components of the application’s memory are heap and stack. A special area inside the heap is called a High-Frequency Heap wherein static members are stored. Static members that are of non-static classes as well are stored in a heap, and then they are shared across all of the instances of the class. Therefore the changes done by one instance get reflected in all of the other instances.

Why Static Classes?

The following are some important points which explain why use Static classes in C#.

  1. Utility and Helper Functions - Static classes are often used to group utility or helper functions that don't require an instance to maintain state. such as mathematical calculations or string manipulations.
  2. Single Instance - Since you cannot instantiate a static class, it ensures that there's only one instance of this class throughout the application lifecycle. Such as a logging service or configuration manager.
  3. Extension Methods - In C#, static classes are used to define extension methods. Extension methods allow developers to add new methods to existing types without modifying those types directly.

Advantages of Static Classes

  1. You will get an error if you declare any member as a non-static member.
  2. When you try to create an instance to the static class, it again generates a compile time error because the static members can be accessed directly with their class name.
  3. The static keyword is used before the class keyword in a class definition to declare a static class.
  4. SStatic class members are accessed by the class name followed by the member name.

Next