Difficulty: Medium
Correct Answer: proc1() can initialize i as well as j.
Explanation:
Introduction / Context:
This snippet contrasts instance and static contexts. The class defines a static field i
and an instance field j
, plus an instance method, a static method, and a static constructor. We must reason about which assignments are legal.
Given Data / Assumptions:
proc1()
is an instance method: it has access to both static and instance members.proc2()
is static: it has no implicit instance (this
), so it cannot refer to instance fields.
Concept / Approach:
An instance method may freely access static and instance members. A static method may access only static members unless given an explicit instance. Static constructors can access only static members.
Step-by-Step Solution:
proc1()
can assign to static i
.B: True — proc1()
can set both i
and j
.C: False — proc2()
cannot reference instance field j
without an instance.D: False — static constructors are legal in C#.E: False — same reason as C; proc2()
can set i
but not j
.
Verification / Alternative check:
Compiling this code will produce errors at the references to j
in proc2()
and in the static constructor.
Why Other Options Are Wrong:
Common Pitfalls:
Attempting to set instance fields in static contexts or forgetting static constructors cannot reference instance state.
Final Answer:
proc1() can initialize i as well as j.
Discussion & Comments