Updated on Kisan Patel
If you want to restricting access to a particular member of the class. There are 5 access modifiers that can be applied to any member of the class.
Access Modifiers | Descriptions |
---|---|
private | Private members have the least access permission level; you can either access them within the body of the class or in the structure in which they are defined. |
protected internal | This type of member can be accessed from the current assembly. |
internal | Can only the current assembly can access these members |
protected | Can be accessed from a containing class. |
public | Allows public access to members both inside and outside of a class without any restrictions. |
For Example,
using System; namespace ConsoleApp { class ScopeDemo { static void Main(string[] args) { myClass myObj = new myClass(); myObj.strClassName = "Hello World"; myObj.RollNo = 55; } } class myClass { public string strClassName; private int age; internal int RollNo; public void SetClassName(string strName) { strClassName = strName; RollNo = 50; } } }
strClassName
variable is a public
, So you can access strClassName
variable on whole program.age
is private
, So you can not access age variable outside myClass
class.RollNo
is internal
variable, So RollNo
variable can be accessed within ConsoleApp assembly.If you don’t mark any member of class with an access modifier; it will be treated as a private member.