C# ยท Chapter 33 of 46

C# Static Members

The static keyword makes a member belong to the class itself rather than to any individual object. Static fields are shared across all instances, and static methods can be called without creating an object.

Static members are useful for utility functions (like Math.Sqrt) or data that should be shared across all instances, like a counter tracking how many objects have been created.

Syntax
static type field;
static returnType Method() { }

Static fields

A static field is shared by all instances of a class. Changing it through one object affects the value seen by all others, since there's only one copy in memory.

Static methods and classes

A static method belongs to the class and is called using the class name, not an object, like `Math.Sqrt(9)`. An entire class can be marked static if it should never be instantiated, like a utility class.

Example 1 (csharp)
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);
  }
}
Output
2

count is static, so it's shared across all Counter objects and increments with each new instance.

Example 2 (csharp)
using System;

class MathHelper {
  public static int Square(int n) {
    return n * n;
  }
}

class Program {
  static void Main() {
    Console.WriteLine(MathHelper.Square(5));
  }
}
Output
25

Square() is called directly on the class without creating a MathHelper object.

Key points

  • static members belong to the class, not to individual objects.
  • Static fields are shared across all instances of the class.
  • Static methods are called using the class name, not an object reference.
  • A static class cannot be instantiated with `new`.
๐Ÿ’ก Note: The Main() method itself is static, which is why it can run without an object being created first.

๐Ÿ“ Quick Quiz

1. What does a static field belong to?

2. How do you call a static method?

3. Can a static class be instantiated with new?