C# Program to Illustrate the use of Access Modifiers – Programming, Pseudocode Example, C# Programming Example
C# Programming Languages

C# Program to Illustrate the use of Access Modifiers

What are Access Modifiers in C#

In C#, access modifiers are keywords that specify the accessibility of a class, method, property, or field. There are four access modifiers in C#: public, private, protected, and internal.

  • public: A class, method, property, or field that is marked as public is accessible from anywhere within the project.
  • private: A class, method, property, or field that is marked as private is only accessible within the class in which it is defined.
  • protected: A class, method, property, or field that is marked as protected is only accessible within the class in which it is defined, and any derived classes.
  • internal: A class, method, property, or field that is marked as internal is only accessible within the project in which it is defined.

By default, classes, methods, properties, and fields are private. If no access modifier is specified, it is assumed that the member is private.

Here is an example of how to use access modifiers:

In this example, the name field is private, so it can only be accessed within the Student class. The Name property is public, so it can be accessed from anywhere within the project. The DoSomething method is private, so it can only be called within the Student class. The DoSomethingElse method is public, so it can be called from anywhere within the project.

Example : Here is an example of a C# program that illustrates the use of access modifiers:

In this example, the Student class has two private fields: name and age. These fields can only be accessed within the Student class. To allow external access to these fields, the Student class has two public properties: Name and Age. These properties provide getter and setter methods for the private fields.

In the Main method, we create a new instance of the Student class and set the Name and Age properties. We then use the getter methods of the Name and Age properties to retrieve the student’s name and age and print them to the console.

This program will output the following:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.