How To Define Accessibility And Scope In C#

In this blog, we shall see the scope of access modifiers and uses of it.

 

From this blog, we will learn the points given below.
  • Introduction about access modifiers
  • Scope
  • Types
  • Rules to be followed
  • Example

Let start with brief introduction about access modifiers

Introduction

By using access modifiers, you can define the scope of the class members in your Application. It is important to understand how access modifiers work because they affect your ability to use a class and its members.

Scope

Scope means the region of code, which an element of the program can be referenced. Let's say, for example, the weight member of the Lion class can be accessed only within Lion Class.

Therefore, the scope of the weight member is Lion class.

Also, items which are nested within the other items are within the scope of those items. Let's say, in case Lion is within MainClass class and therefore it can be referenced from anywhere within MainClass class.

Types of Access Modifiers

Public

Access is not limited, any other class can access a public member.

Private

Access is limited to the containing type, only the class containing the member can access the member.

Internal

Access is limited to this assembly; classes within the same assembly can access the member.

Protected

Access is limited to the containing class and to the types derived from the containing class.

Protected Internal

Access is limited to the containing class, derived classes or to the classes within the same assembly as containing data.

While working with access modifiers, we need to take note of some key points, as shown below.

  • Namespaces are always public.
  • Classes are always public.
  • Class members are private by default.
  • Only one modifier can be declared on a class member, even protected internal comprises of two words, it is a access modifier.
  • The scope of a member is never larger than that of its containing type.

The accessibility of our class members determines the set of behaviors, which the user of our class sees. If we define a class member as private, the user of the class cannot see or use the member.

We should make public only those items, which the user of our classes needs to see. 

Example 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Microsoft.SharePoint;  
  6. namespace GetSharePointListNames {  
  7.     class Program {  
  8.         public class Lion {  
  9.             public int age;  
  10.             private int weight;  
  11.         }  
  12.         static void Main(string[] args) {  
  13.             Lion ZooLion = new Lion();  
  14.             ZooLion.age = 7;  
  15.             //the following line causes a compilation error  
  16.             ZooLion.weight = 200;  
  17.         }  
  18.     }  
  19. }   

We can see the error, as shown below.

 
Thanks for reading my blog.