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: private and public.

Private Visibility

  • private members are internal to the class and can only be accessed from within the class itself.

  • If a field like ID is private, it can be set within the Student class (e.g., in the constructor) but not from outside the class (e.g., in the Program class).

Public Visibility

  • public members 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 to internal.

  • For our current purposes, internal is treated the same as public.

  • However, members of a class (fields, methods) default to private if 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 declared public.

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 calculateGPA method can be made private and invoked from within the setGPA method.

  • This improves code organization and readability, even if the simplification isn't dramatic.

Controlling Access with Public Methods and Private Fields

  • Fields like GPA can be made private to control how they are accessed and modified.

  • Public methods like setGPA and getGPA can then be used to provide controlled access to the GPA value.

  • This allows for validation, calculation, or other logic to be applied when setting or getting the GPA.

  • For instance, setGPA might require an array of grades as input and calculate the GPA based 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 public and private visibility levels.

  • internal is essentially equivalent to public for 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 Student class), it's best practice to move each class into its own file.

  • The file name should match the class name (e.g., Student.cs for the Student class).

  • 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.