Static Members
Static members belong to the whole class instead of one object, like the school bell that rings for everyone. You use them through the class name without making an object.
In this page:
Syntax
class ClassName
{
public static type Field;
public static ReturnType MethodName() { }
}
ClassName.Field;
ClassName.MethodName(); // no object needed
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Trying to access an instance member from a static method without an object.
- Expecting each object to have its own copy of a static field, when it is shared by all.
- Using static everywhere, which makes code hard to test.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: