Runtime & concurrency
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Reflection;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
Console.WriteLine("before");
Console.WriteLine($"first:{Counter.Next()}");
Console.WriteLine($"second:{Counter.Next()}");
static class Counter
{
private static int value;
static Counter() { Console.WriteLine("init"); value = 2; }
public static int Next() => ++value;
}
Reveal answer and reasoning
The output is before, init, first:3, and second:4. The first host line does not access Counter. Before the first Next invocation can proceed, the explicit static constructor prints init and sets value to two. Next increments that state to three, then the second invocation increments it again to four. The initialized type retains its state and does not rerun a successful static constructor for the second call.
This trace depends on the actual explicit-constructor declaration and access sequence, not on source-file position or a measured JIT tier. A common wrong answer prints first before init or resets the state to two for every call. Removing the explicit constructor changes the reasoning and should be a separate experiment rather than an assumed equivalent rewrite. The program also does not inspect unrelated types or demonstrate generic static-state sharing, so its one initialization line should not be generalized into one initializer for an entire application.
What a strong answer covers
- Initialization occurs before the first Next body.
- The constructor sets two, then increments produce three and four.
- Successful initialization is retained for this type.
Common pitfall
Treating static construction as either ordinary per-call work or a source-file-order event.
Follow-up questions
- What does a third Next call print?
- What might differ after replacing the explicit constructor with field initialization only?
Self-review
Choose what to revisit. These marks are your own assessment and are separate from lesson completion.