One of the most important concepts in C# and object-oriented programming is the static keyword. Almost every .NET developer uses static members regularly, but many beginners struggle to fully understand what a static variable is, where to use it, when to use it and when not to use it.
What is static?
Normally in object-oriented programming, when we create objects, every object gets its own copy of variables and methods. When you mark a variable, method, or class as static, you are telling the .NET runtime that this member should exist only once in the memory. You do not need to create an object using the new keyword to access it.
So, we can say that static members are:
- Shared across all objects.
- Created only once in memory.
- Accessible using the class name.
Lifetime and Scope
Understanding when a static member "lives" and "dies" is key to avoiding memory leaks.
- Lifetime: Static members are initialized the first time the class is referenced. They stay in memory for the entire life of the application. They are only destroyed when the program closes.
- Scope: Static members are visible based on their access modifier (
public,private, etc.), but they are always accessed through the Class Name.
Common Use Cases:
- Counters: Keeping track of how many objects have been created.
- Shared Configuration: A global settings value like
AppVersion. - Caching: Storing data that is expensive to calculate so all objects can reuse it.
1. Static Members
Static variables are used when you need to store data that should be shared across all instances of a class.
Here is an example of static variables.
public class Student
{
public string Name;
// Static variable: Shared by ALL students
public static int StudentCount = 0;
public Student(string name)
{
Name = name;
StudentCount++; // Increment the shared counter
}
}In this example, the StudentCount field is a static member. It is shared across the objects.
Accessing Static Members: Class Name vs. Object
This is the most common point of confusion for beginners. Static members belong to the Class, not the Object.
Student s1 = new Student("Alice");
// ❌: Static member 'StudentCount' cannot be accessed with an instance reference
Console.WriteLine(s1.StudentCount);The correct way is:
Student p1 = new Student("Alice");
Student p2 = new Student("Bob");
// âś… ACCESS VIA CLASS NAME
Console.WriteLine(Student.StudentCount); // Output: 2If we want to access the static member from withing the class, we can simply access it with its name.
public class Student
{
public string Name;
// Static variable: Shared by ALL students
public static int StudentCount = 0;
public Student(string name)
{
Name = name;
StudentCount++; // Increment the shared counter.
// âś… Correct.
Console.WriteLine("Total Students " + StudentCount);
// âś… Correct.
Console.WriteLine("Total Students " + Student.StudentCount);
// ❌ Wrong.
Console.WriteLine("Total Students " + this.StudentCount);
}
}2. Static Members
A static method is a function that can be called without creating an object. Because it doesn't belong to a specific object, it cannot access non-static (instance) variables.
In the below given example, we have a non-static class called Calculator and two member variables:
- TaxRate - Instance variable (Cannot be accessed from a static method).
- GlobalDiscount - A static Variable.
public class Calculator
{
public int TaxRate = 10; // Instance variable
public static int GlobalDiscount = 5; // Static variable
// CORRECT: Static method using static variable
public static int GetDiscountedPrice(int price)
{
return price - GlobalDiscount;
}
// WRONG: Static method trying to use instance variable
public static int GetTaxedPrice(int price)
{
// ERROR: An object reference is required for the non-static field 'TaxRate'
return price + (price * TaxRate / 100);
}
}The GetTaxedPrice is a static method. So, it cannot access any Instance variables like TaxRate.
3. Static Class
A static class is a class that cannot be instantiated. You cannot use the new keyword with it. Every single member inside a static class must also be marked as static.
Why use a static class? They are perfect for "Utility" or "Helper" functions. Examples in .NET include Console.WriteLine, System.Math or System.Convert.
Example:
public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string gelsius)
{
double celsius = double.Parse(gelsius);
return (celsius * 9 / 5) + 32;
}
}
// Usage:
double f = TemperatureConverter.CelsiusToFahrenheit("30");Member Comparison Table
| Feature | Static Member | Instance Member |
|---|---|---|
| Memory | One copy for the whole app. | New copy for every new object. |
| Access | ClassName.Member |
objectName.Member |
| Initialization | When class is first loaded. | When new is called. |
| Usage | Global helpers, counters. | Unique data (Name, Age, ID). |
Practice Questions
1. You have a class DatabaseConnection. You want to ensure there is a variable that stores the TotalConnectionsOpened across the whole app. Should it be static?
- Answer: Yes. Since you want to track the total across all instances, it must be
static.
2. Can a static method call a non-static method directly?
- Answer: No. A static method exists without an object. A non-static method requires an object to function. Therefore, the static method wouldn't know "which" object's method to call.
3. What happens if you try to use the new keyword on a static class?
- Answer: You will get a compilation error. Static classes are sealed and cannot be instantiated.
4. Look at this code. Will it work?
public class User
{
public static string SiteName = "MySite";
public void PrintName()
{
Console.WriteLine(SiteName);
}
}
- Answer: Yes! Instance methods (like
PrintName) are allowed to access static variables.