Static Types (Part 3/3): Initializing Static Members with a Static Constructor
2 min readMar 13, 2024
The final topic I want to discuss regarding Static Types is how to initialize static members using a static constructor.
Static constructor demonstration
To demonstrate this concept, I’ve created a simple script featuring a Student class that defines a student and a Test class used to execute the script.
public class Student
{
public int studentID;
public string firstName, lastName;
public string major;
public static string university;
public Student()
{
Debug.Log("Instance member initialized");
}
static Student()
{
university = "Cape Breton University";
Debug.Log("Intialized static member");
}
}
public class Test : MonoBehaviour
{
private void Start()
{
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
}
}
Each student object will have its own ID, first and last name, and major (instance members), but they will share a single university (static member). Upon running the script, the static constructor should execute first and only once, followed by the non-static constructor, which will execute three times.
And here’s the result: