Static Members
In this page:
Static Members
static fields and methods belong to the class itself, not to any individual object, and are shared across every instance. You call them through the class name rather than an object reference. Static members are useful for counters, utility methods, and shared configuration.
Note: A static field is a good way to count how many instances of a class have been created.
Example: Static Members
using System;
class Counter
{
public static int InstanceCount = 0;
public Counter()
{
InstanceCount++;
}
public static int Double(int n) => n * 2;
}
class Program
{
static void Main(string[] args)
{
new Counter();
new Counter();
new Counter();
Console.WriteLine(Counter.InstanceCount);
Console.WriteLine(Counter.Double(21));
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: