Static fields
Learn that static fields are shared at the class level.
Static fields
A static field is data that belongs to the class itself. Instance fields keep a separate copy per object, while static fields keep a single copy shared across all instances.
To make a field static use the static keyword: public static int Count;. This field exists even before any new instance is created. Static fields are a good fit for counters, running totals and any state shared by all instances.
Accessing static fields
You don't need an instance to reach a static field; you write the class name: Counter.Count. You can also go through an instance (counter.Count) but this is discouraged and the compiler warns.
Static fields are set to their default value when the class loads: 0 for int, false for bool, null for reference types. You may also assign an initial value: public static int Count = 10;.
Exercise Counter class
Add a public static int Count = 0; field to the Counter class. The constructor should increment Count each time it runs. In Main, create two instances and print Counter.Count.
Show example solution
Add `public static int Count = 0;` to Counter. In the ctor write `Count++;`. In Main create two `new Counter()` and call `Console.WriteLine(Counter.Count);`.
Example solution:
using System;
class Counter
{
public static int Count = 0;
public Counter()
{
Count++;
}
}
class Program
{
static void Main()
{
new Counter();
new Counter();
Console.WriteLine(Counter.Count);
}
}
Test yourself
-
Which is a valid static field declaration?
- public int Count;
- static Count;
- public static int Count;
- public static Count int;
Show answer
public static int Count; — Correct. `public static int Count;` has both the `static` keyword and a type.
-
Fill in the blank: static field declaration
class Counter { public ____ = 0; }Show answer
class Counter { public static int Count = 0; } -
Match: static field concepts
- static field
- shared across all instances
- instance field
- separate copy per object
- Counter.Count
- access via class name
- new Counter()
- creates a new instance