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 class Program
{
public static void Main(string[] args)
{
DateTime date = DateTime.Now;
Console.WriteLine($"Formatted Date: {UtilityHelper.FormatDate(date)}");
}
}
public static class UtilityHelper
{
public static string FormatDate(DateTime date)
{
return date.ToString("MMMM dd, yyyy", CultureInfo.InvariantCulture);
}
}
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
Top comments (0)