Instance fields, instance methods, and accessibility in C# — consider the code and choose the correct statements. namespace CuriousTabConsoleApplication { class Sample { public int index; public int[] arr = new int[10]; public void fun(int i, int val) { arr[i] = val; } } class MyProgram { static void Main(string[] args) { Sample s = new Sample(); s.index = 20; // Sample.fun(1, 5); // static-style call (invalid) s.fun(1, 5); // instance call (valid) } } } Which of the following statement sets are correct?

Difficulty: Easy

Correct Answer: 2) The call s.fun(1, 5) will work correctly. 4) The call Sample.fun(1, 5) cannot work since fun() is not static.

Explanation:


Introduction / Context:
This scenario distinguishes between instance members and static members in C#. It also touches on accessibility of fields and arrays declared as public.



Given Data / Assumptions:

  • index is a public instance field.
  • arr is a public instance array field of length 10.
  • fun(int i, int val) is an instance method (non-static) that writes into the array.


Concept / Approach:
Instance members must be accessed through an instance (object). Static members are accessed via the type name. Public accessibility allows direct access, but that does not change instance vs. static binding rules.



Step-by-Step Solution:

Statement 1) is false: s.index = 20 is valid because index is public (no error).Statement 2) is true: s.fun(1, 5) correctly assigns arr[1] = 5 on the same instance.Statement 3) is false: Sample.fun(1, 5) attempts to call an instance method as if it were static; it will not compile and therefore cannot set anything.Statement 4) is true: the call cannot work since fun() is not static.Statement 5) ('arr cannot be public') is false: arrays can be public fields, though encapsulation best practices discourage it.


Verification / Alternative check:
Attempt to compile Sample.fun(1, 5); the compiler reports that an object reference is required for the non-static field, method, or property.



Why Other Options Are Wrong:
They include false statements (1, 3, 5) or omit the valid statement 2.



Common Pitfalls:
Confusing 'public' with 'static'; public only controls accessibility, not whether a member belongs to the instance or the type.



Final Answer:
2) The call s.fun(1, 5) will work correctly. 4) The call Sample.fun(1, 5) cannot work since fun() is not static.

More Questions from Classes and Objects

Discussion & Comments

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