C#.NET — Access modifiers and member access within a class. Given: class Sample { private int i; public float j; private void DisplayData() { Console.WriteLine(i + " " + j); } public void ShowData() { Console.WriteLine(i + " " + j); } } Which statement is correct?
-
Aj cannot be declared as public.
-
BDisplayData() cannot be declared as private.
-
CDisplayData() cannot access j.
-
DShowData() cannot access to i.
-
EThere is no error in this class.
Answer
Correct Answer: There is no error in this class.
Explanation
Introduction / Context:This problem verifies understanding of access modifiers and intra-class accessibility in C#. It checks whether private and public members can coexist and whether methods can access fields with different access levels.
Given Data / Assumptions:
- Field i is private; field j is public.
- DisplayData() is private; ShowData() is public.
Concept / Approach:Inside the same class, all members (regardless of their own access modifier) can access each other. Access modifiers only restrict visibility from outside the class (or from derived classes/assemblies depending on modifier), not within it.
Step-by-Step Solution:
Private field i and public field j are both legal.A private method DisplayData() is legal and can access both i and j.A public method ShowData() is legal and can also access both i and j.Therefore, the class compiles and runs without errors.Verification / Alternative check:Instantiate Sample and call ShowData(); you will see output containing both i (default 0) and j (default 0) unless set elsewhere.
Why Other Options Are Wrong:(a) and (b) are false restrictions; (c) and (d) misinterpret intra-class access rules.
Common Pitfalls:Believing a private method cannot access public members, or vice versa. Inside a class, access is unrestricted among members.
Final Answer:There is no error in this class.