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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Microsoft.SharePoint;
- namespace GetSharePointListNames {
- class Program {
- public class Lion {
- public int age;
- private int weight;
- }
- static void Main(string[] args) {
- Lion ZooLion = new Lion();
- ZooLion.age = 7;
-
- ZooLion.weight = 200;
- }
- }
- }
We can see the error, as shown below.
Thanks for reading my blog.