7.4. Static constructors (Java static initializers)

C# has two different kinds of constructors, static and instance – depending on whether they are declared with the static keyword or not. While C# instance constructors are similar to Java constructors, C#'s static constructors are similar to Java static initializers. Static constructors, like their instance counterparts, must have the same name and case as the class of which it is a member.

However, unlike instance constructors, static constructors:

  • cannot have parameters;

  • cannot have accessibility modifiers;

  • cannot be called explicitly.

Static constructors are automatically invoked before the first static class member is utilized. Here is an example of a static constructor.

 1: using System; ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.