Unlock the Power of the Static Keyword in C#!

posted Originally published at dev.to 2 min read

What’s Static ?

The static keyword in C# is used for defining classes, variables, functions, and properties. As a keyword modifier, it offers several important features and benefits. Here’s an overview of its key advantages and uses.


 public class SuperMath

{
     public static double Pi = 3.14159;
}
 
public class Circle : SuperMath

{
    private double radius;

    public Circle(double radius)
    
    {
        this.radius = radius;
    }

    public double CalculateCircumference()
    
    {
        return 2 * Pi * radius;
    }

    public double CalculateArea()
    
    {
        return Pi * Math.Pow(radius, 2);
    }
}
 
public class Cylinder : SuperMath

{
    private double radius;
    private double height;

    public Cylinder(double radius, double height)
    
    {
        this.radius = radius;
        this.height = height;
    }

    public double CalculateSurfaceArea()
    
    {
        return 2 * Pi * radius * (radius + height);
    }

    public double CalculateVolume()
    
    {
        return Pi * Math.Pow(radius, 2) * height;
    }
}

public static class DatabaseManager

  {
    public static string ConnectionString { get; private set; }
    
    public static int MaxPoolSize { get; private set; }
    
    private static readonly ILogger<DatabaseManager> _logger;


     static DatabaseManager()
        
        {
            
            using var loggerFactory = LoggerFactory.Create(builder =>
            
            {
                builder.AddConsole();
            });
    
            _logger = loggerFactory.CreateLogger<DatabaseManager>();
    
           
            ConnectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
            
            MaxPoolSize = 100;
    
            
            Console.WriteLine("Static constructor called. Database settings initialized.");
            
            _logger.LogInformation("Static constructor called. Database settings initialized at {Time}", DateTime.Now);
        }
    }
    
     
    public class Program
    
    {
        public static void Main(string[] args)
        
        {
            // Accessing the static members to trigger the static constructor
            
            Console.WriteLine(DatabaseManager.ConnectionString);
            
            Console.WriteLine(DatabaseManager.MaxPoolSize);
        }
    }

using System;


class Program

{
    public static void Main(String[] args)
    
    {
    
        Console.WriteLine(Math.Sqrt(3 * 3 + 4 * 4));
    
    }
}
 


using static System.Console;

using static System.Math;

class Program

{
     public static void Main(String[] args)
     
     {
  
        WriteLine(Sqrt(3 * 3 + 4 * 4));
  
     }
}

Memory Allocation

Instance Variables vs. Static Variables :

Instance variables are part of each object created from the class, with each object having its own copy. Static variables, however, are allocated once per class, shared by all instances.

Memory Management :

Static variables help manage memory efficiently by reducing the number of copies needed for variables that should be shared across instances. This is useful for constants, configuration settings, or counters that track class-level data.


Summery

Static Variables

  • Belong to the Class : Shared across all instances of the class.

  • Common State : Useful for storing data or state common to all instances.

  • Single Copy : Only one copy exists, regardless of the number of instances.
    Memory Efficiency: Saves memory by avoiding duplication of common data.

Static Methods

  • Class-Level Methods : Belong to the class rather than any instance.

  • Access Static Members : Can only access static variables and other static methods.

  • Utility Functions : Ideal for operations related to the class as a whole, such as utility or helper functions.

  • No Instance Required : Can be called without creating an instance of the class.

Static Constructor

  • Initialize Static Members : Used to initialize static variables.

  • Automatic Call : Called automatically before any static members are accessed or static methods are called.

  • Single Execution : Executed once, when the class is first accessed.

  • No Parameters : Cannot take parameters.

Static Modifier

  • Using Static Directive : Allows access to static members and nested types without specifying the class name.

  • Scope Simplification : Simplifies code by eliminating the need to repeatedly specify the type name.


Sources

If you read this far, tweet to the author to show them you care. Tweet a Thanks
Hussein i gotta say, the examples really helped me get the concept. i always wondered how static variables and methods behave compared to instance ones. so, i get that static variables are shared across all instances, but how do you handle potential issues if two different classes modify the same static variable? i mean, wouldn’t it mess with the state? anyway, mad props to the writer for breaking it down so well, definitely making the concept less intimidating. cool stuff!

Thank you .

This is exactly one of the problems faced by this type of variable, which we previously used in the Singleton pattern, which caused very serious problems ☠️. This type of variable, no matter how many layers of protection it has, such as synchronization, privacy, and even private generation (private constructor), can be broken by any skilled programmer, for example, through reflection ♟.

Therefore, the best solution for such variables was to place them in a variable type called Enumeration, which here prevents any modification of the value after it is assigned. Note that the creation/generation process that uses static is called "eager initialization."

Here's a link that explains the usefulness of Enumeration in C# :
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum

More Posts

Building Robust API Clients in C# with Refit

Odumosu Matthew - Jan 6

Modern Use OF Telnet with an example In dotnet,The Rise and Fall of Telnet: A Network Protocol's Journey

Moses Korir - Mar 12

Understanding Equality in C# with IEquatable, Not Equals and ==

Spyros - Feb 6

How To Create Custom Middlewares in ASP.NET Core

Anton Martyniuk - May 13, 2024

Exploring Modern Web Development with Blazor: A Friendly Guide

Kenneth Okalang 1 - Mar 13
chevron_left