Summary - Static members
Combine static class, methods and readonly to write a Configuration helper.
Summary - Static members
In this group you learned static members: a static field is shared across all instances, a static method is called via the class name, a static class cannot be instantiated. const holds a compile-time constant, readonly a runtime immutable value. A static constructor runs once when the class loads.
Static members suit helper operations that don't depend on instance state, shared counters and immutable values. If you need instance state, use a normal class instead.
Exercise Counter class (summary)
Add a public static int Count = 0; field to Counter. The Increment static method does Count++. In Main, call Counter.Increment() twice and print Counter.Count.
Show example solution
Add `public static int Count = 0;` to Counter. In Increment write `Count++;`. In Main write `Counter.Increment(); Counter.Increment(); Console.WriteLine(Counter.Count);`.
Example solution:
using System;
class Counter
{
public static int Count = 0;
public static void Increment()
{
Count++;
}
}
class Program
{
static void Main()
{
Counter.Increment();
Counter.Increment();
Console.WriteLine(Counter.Count);
}
}
Exercise Helper class (summary)
Define a static class Helper. Add a public static int Add(int a, int b) method whose body is return a + b;. In Main, call Helper.Add(3, 4) and print the result.
Show example solution
Add `static class Helper { public static int Add(int a, int b) { return a + b; } }`. In Main write `Console.WriteLine(Helper.Add(3, 4));`.
Example solution:
using System;
static class Helper
{
public static int Add(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main()
{
Console.WriteLine(Helper.Add(3, 4));
}
}
Next step
Static members simplify many real cases: singleton patterns, extension methods and helper libraries. The next group dives deeper into constants with const, readonly, static readonly and enum.
Remember: static members can hurt testability; don't overuse them. Prefer a normal class when you need instance state.
Test yourself
-
Which statement about static members is correct?
- A static class cannot be instantiated.
- A static method can access instance fields.
- A static field holds a separate copy per instance.
- A static constructor runs on every instance creation.
Show answer
A static class cannot be instantiated. — Correct. A static class cannot be instantiated; all members must be static.
-
Fill in the blank: static method
class Helper { public static int Add(int a, int b) { return ____; } }Show answer
class Helper { public static int Add(int a, int b) { return a + b; } }