Skip to main content

Command Palette

Search for a command to run...

C# learning notes- static

Published
1 min readView as Markdown

static

General concept

  • Associated with the class, NOT an instance.

Static class

  • A static class CANNOT be instantiated.
  • Its members are accessed by the class name, instead of the instance name, like Math.PI.

Access Static members

  • Static to static Only
  • A static method can ONLY access static members.

Static constructor

To trigger the static constructor?

  • Once per type, not per instance.
  • One of the following two conditions:
// 1. the type is instantiated
public static void Main() {
  Forest f  = new Forest(); 
}
// 2. a static member is accessed
// Define() is a static method
public static void Main() {
  Forest.Define(); 
}
D

Here are a couple more for you...

  • Static classes are sealed so cannot be inherited. They cannot inherit from any class except Object.
  • Static classes live for the lifetime of your application so don't store large quantities of data in them.