C# Static Members
Normally each object has its own copy of every field. A static member is different: it belongs to the class itself, and there is exactly one copy shared by the whole program. You access it through the class name rather than through an object — just like Math.PI or Console.WriteLine.
Static fields
A static field is ideal for data that is about the class as a whole, such as a counter of how many objects were created:
using System;
var a = new Ticket();
var b = new Ticket();
var c = new Ticket();
Console.WriteLine(quot;a={a.Number}, b={b.Number}, c={c.Number}");
Console.WriteLine(quot;Tickets issued: {Ticket.Issued}");
class Ticket
{
public static int Issued; // shared by all tickets
public int Number { get; } // one per ticket
public Ticket()
{
Issued++;
Number = Issued;
}
}a=1, b=2, c=3
Tickets issued: 3
Static methods
A static method does not operate on a particular object, so it cannot use this or instance members directly. It is a good fit for utility functions whose result depends only on their parameters:
using System;
Console.WriteLine(Temperature.ToFahrenheit(25));
Console.WriteLine(Temperature.ToCelsius(212));
Console.WriteLine(Temperature.IsFreezing(-3));
static class Temperature
{
public static double ToFahrenheit(double c) => c * 9 / 5 + 32;
public static double ToCelsius(double f) => (f - 32) * 5 / 9;
public static bool IsFreezing(double c) => c <= 0;
}77
100
True
Static classes
A class marked static can contain only static members and can never be instantiated (new Temperature() would not compile). The .NET library uses static classes for collections of helpers: Math, Console, File, Convert.
| Regular class | Static class | |
|---|---|---|
Can create objects with new |
Yes | No |
| Instance members | Allowed | Not allowed |
| Static members | Allowed | Required |
| Can be inherited | Yes | No |
Static members in a regular class
Regular classes often mix instance and static members. A common pattern is a static factory method that creates objects in a descriptive way, plus shared constants:
using System;
var red = Color.FromHex("#FF0000");
var gray = Color.Gray(128);
Console.WriteLine(red);
Console.WriteLine(gray);
Console.WriteLine(Color.White);
Console.WriteLine(quot;Colors created: {Color.Created}");
class Color
{
public static readonly Color White = new Color(255, 255, 255);
public static int Created { get; private set; }
public byte R { get; }
public byte G { get; }
public byte B { get; }
private Color(byte r, byte g, byte b)
{
R = r; G = g; B = b;
Created++;
}
public static Color Gray(byte level) => new Color(level, level, level);
public static Color FromHex(string hex) => new Color(
Convert.ToByte(hex.Substring(1, 2), 16),
Convert.ToByte(hex.Substring(3, 2), 16),
Convert.ToByte(hex.Substring(5, 2), 16));
public override string ToString() => quot;rgb({R}, {G}, {B})";
}rgb(255, 0, 0)
rgb(128, 128, 128)
rgb(255, 255, 255)
Colors created: 3
The constructor is private, so the only way to get a Color is through the static factories — a technique that gives you full control over creation.
Static constructors
A static constructor runs once, automatically, before the class is first used. Use it to initialise static data that needs more than a simple expression:
using System;
Console.WriteLine("Program starts");
Console.WriteLine(Lookup.Squares[12]);
Console.WriteLine(Lookup.Squares[20]);
class Lookup
{
public static readonly int[] Squares;
static Lookup()
{
Console.WriteLine("Building lookup table...");
Squares = new int[21];
for (int i = 0; i <= 20; i++) Squares[i] = i * i;
}
}Program starts
Building lookup table...
144
400
The message appears only once, right before the first access to Lookup.
using static
The using static directive imports the static members of a class so you can call them without the class name:
using static System.Math;
double hyp = Sqrt(Pow(3, 2) + Pow(4, 2)); // 5Note: Static fields are shared state. Overusing mutable static fields makes code harder to test and can cause problems with multiple threads. Prefer
static readonlyorconstfor shared values, and pass objects around for everything else.
Test yourself
How many copies of a static field exist?
- One per object
- One for the whole class
- One per method
- None until assigned
Which of these is NOT allowed inside a static method?
- Calling another static method
- Using a local variable
- Accessing
this - Reading a static field
What happens if you write new Math()?
- Creates a Math object
- Compile error: cannot create an instance of a static class
- Returns null
- Runtime exception