C#.NET — Static constructor vs static method: determine the order of outputs. Program: namespace CuriousTabConsoleApplication { class Sample { static Sample() { Console.Write("Sample class "); } public static void CuriousTab1() { Console.Write("CuriousTab1 method "); } } class MyProgram { static void Main(string[] args) { Sample.CuriousTab1(); } } } What will be printed?

Difficulty: Easy

Correct Answer: Sample class Tab1 method

Explanation:


Introduction / Context:
This question examines when the static constructor runs relative to the first access to a type, compared to the invocation of a static method, and how that affects the order of outputs on the console.


Given Data / Assumptions:

  • The class Sample defines a static constructor and a static method CuriousTab1().
  • Main calls Sample.CuriousTab1().
  • Both outputs are written with Console.Write (no newline), so the order is visible in a single line.


Concept / Approach:
In C#, the static constructor executes automatically once, before the first use of the type (first access to any static member). Therefore, referencing Sample.CuriousTab1 triggers the static constructor first, then the static method body runs.


Step-by-Step Solution:

First type access: before calling CuriousTab1(), the runtime runs static Sample(), writing "Sample class ". Then the static method executes, writing "CuriousTab1 method ". The combined output (ignoring spacing differences in the answer set) corresponds to “Sample class Tab1 method”.


Verification / Alternative check:
Add another call to Sample.CuriousTab1(); you will see the static constructor does not repeat, confirming it runs only once per AppDomain.


Why Other Options Are Wrong:

  • B/C miss one of the two required prints.
  • D reverses the order (incorrect for static constructor semantics).
  • E duplicates the static constructor (it runs only once).


Common Pitfalls:
Thinking static constructors run at compile time or on every static call; in reality they run once, just before first use of the type.


Final Answer:
Sample class Tab1 method

More Questions from Constructors

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion