Visibility in C# and Class Organization
Visibility Levels in C
Introduction to Visibility
Visibility refers to the accessibility of class members (fields, methods, etc.) from different parts of the code.
At this stage, we focus on two primary visibility levels:
privateandpublic.
Private Visibility
privatemembers are internal to the class and can only be accessed from within the class itself.If a field like
IDis private, it can be set within theStudentclass (e.g., in the constructor) but not from outside the class (e.g., in theProgramclass).
Public Visibility
publicmembers are accessible from anywhere, both inside and outside the class.
Internal Visibility
When no visibility is explicitly specified for a class (e.g.,
class Student), it defaults tointernal.For our current purposes,
internalis treated the same aspublic.However, members of a class (fields, methods) default to
privateif no visibility is specified.If a constructor has no visibility modifier, it defaults to
private, leading to access errors if external code tries to use it. Therefore, constructors are typically declaredpublic.
Private Methods as Helper Methods
Private methods are often used as helper methods within a class to break down complex logic into smaller, more manageable units.
For example, a
calculateGPAmethod can be made private and invoked from within thesetGPAmethod.This improves code organization and readability, even if the simplification isn't dramatic.
Controlling Access with Public Methods and Private Fields
Fields like
GPAcan be made private to control how they are accessed and modified.Public methods like
setGPAandgetGPAcan then be used to provide controlled access to theGPAvalue.This allows for validation, calculation, or other logic to be applied when setting or getting the
GPA.For instance,
setGPAmight require an array of grades as input and calculate theGPAbased on those grades.This approach offers significant benefits from a software architecture perspective by encapsulating data and controlling access to it.
Summary of Visibility Levels
We are primarily concerned with
publicandprivatevisibility levels.internalis essentially equivalent topublicfor our current usage.
Class File Organization
For small classes, it may be acceptable to keep multiple classes in the same file.
However, as classes grow larger (like the
Studentclass), it's best practice to move each class into its own file.The file name should match the class name (e.g.,
Student.csfor theStudentclass).This improves code organization and makes it easier to find specific class definitions.
Creating a New Class File
In Visual Studio, you can add a new class file by selecting "Add New Item" and choosing "Class."
Give the file the same name as the class it will contain.