advertisement
Access Modifiers in C#
Object-oriented programming enables you to restrict access to data members defined in a class so that only specific classes can access them. To specify these restrictions, C# provides access modifiers that allow you to specify which classes can access the data members of a particular class. Access modifiers are specified using c# keywords.
In C#, there are four commonly used access modifiers. These are as follows:
1. Public:-
The public access modifier provides the most permissive access level. The members declared as public can be accessed anywhere in the class as well as from other classes.
public class PublicClass
{
public void PublicMethod()
{
Console.WriteLine("Public Method Called");
}
}
class Program
{
static void Main(string[] args)
{
PublicClass PublicObj = new PublicClass();
PublicObj.PublicMethod();
Console.ReadKey();
}
}
2. Private:-
The private access modifiers provide the least permissive access level. Private members are accessible only within the class in which they are declared.
class privateclass
{
private void privatemethod()
{
console.writeline("private method called");
}
}
class program
{
static void Main(string[] args)
{
PrivateClass PrivateObj = new PrivateClass();
Console.ReadKey();
}
}
3. Protected:-
The protected access modifiers allow the class members to be accessible within the class as well as within the derived classes.
Sub Class Example
class mybaseclass
{
protected void protectedMethod()
{
Console.WriteLine("Protected method in my base
the class called");
}
}
class myderivedclass : mybaseclass
{
public void accessprotectedmethod()
{
protectedMethod();
}
}
class program
{
static void Main(string[] args)
{
myderivedclass derivedObj = new myderivedclass();
derivedObj.accessprotectedmethod();
Console.ReadKey();
}
}
4. Internal:-
The Internal access modifiers allow the class members to be accessible only within the classes of the same assembly. An assembly is a file that is automatically generated by the compiler upon successful compilation of a .NET application.
class internalClass
{
internal void internalMethod()
{
Console.WriteLine("intenal method called");
}
}
class program
{
static void Main(string[] args)
{
internalClass internalObj = new internalClass();
internalObj.internalMethod();
Console.ReadKey();
}
}
advertisement
Conversation
Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!
Join the discussion and share your insights now!
Comments 0