C#.NET — Analyze static vs instance access in the following code and select the correct statement(s): class Sample { static int i; int j; public void proc1() { i = 11; j = 22; } public static void proc2() { i = 1; j = 2; } static Sample() { i = 0; j = 0; } }

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.
  • Static constructors exist in C# and are parameterless; they run once per type.


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:

A: False — 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:

  • A/C/E: Misstate static versus instance access rules.
  • D: Misrepresents C# support for static constructors.


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

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