Access modifiers

All classes, along with their respective attributes and functions, have an access modifier associated with them. An access modifier basically indicates how the respective element will be accessed in the application, both in its own assembly as well as in other assemblies. Collectively, attributes and functions in an application are referred to as class members.

In C#, a class and its class members can acquire the following access modifiers:

  • Public: A class or a class member declared as public can be accessed by all classes in the same assembly as well as by classes in different assemblies present in the application.
  • Private: A class member declared as private can be accessed only in the same class but not outside it.
  • Protected: A class or a class member declared as protected can be accessed inside the class or by classes that inherit from the respective class.
  • Internal: A class or a class member declared as internal can only be accessed by classes in the same assembly but not by outside assemblies.
  • Protected internal: A class or a class member declared as protected internal can only be accessed by classes in the same assembly or by classes present in the outside assembly that inherit from the respective class.
  • Private protected: A class or a class member declared as private protected can only be accessed in the same class or in classes present in the same assembly that inherit from the respective class.

Let's look at the following image to summarize this knowledge about access modifiers. In the following example, we have Assembly A and Assembly B in the application. Assembly A has Class A, which has different functions, each with a separate access modifier. Please refer to the comments against each of the functions to understand which classes under which assemblies can access the respective functions:

Based upon the accessibility level and the security that we wish to embed in the different class members, we can choose either of the previously mentioned access modifiers. To keep some structure and avoid introducing undue complexity, it's advisable to only expose class members to classes that require some information to be shared with the respective class.

In the next section, we will look at the different data types that a class member can acquire.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.159.223