How many access modifiers in c#
In this article, we will learn about the access modifiers in C#.
1. Public Access Modifier in C#
The class member, that is defined as a Public can be accessed by other class members that are initialized outside the class. A public member can be accessed from anywhere even outside the namespace.
public class Vehicle {
public void Color() {
Console.WriteLine("Vehicle color red");
}
}
2. Private Access Modifier in C#
The private access modifier restrict the member variable or function to be called outside of the parent class. A private function or variable cannot be called outside of the same class. It hides its member variable and method from other class and methods.
public class Vehicle {
private string Name;
public void Color() {
Console.WriteLine("Vehicle color red");
}
}
In the above example, you cannot call name variable outside the class because it is declared as private.
3. Protected Access Modifier in C#
The protected access modifier hides its member variables and functions from other classes and objects. This type of variable or function can only be accessed in child class. It is very important while we implementing inheritance in c#.
public class Vehicle {
protected string Name = "Vehicle name is Car";
public void Color() {
Console.WriteLine("Vehicle color red");
}
}
class Program : Vehicle {
public static void Main(string[] args)
{
Program p = new();
Console.WriteLine(p.Name);
Console.ReadLine();
}
}
In above example, We first inherits Vehicle class in Program class and then we created Program class object p then we access Name variable. In order to access protected member in other class we must need to inherits that class first, then and then we can used that member in other class.
4. Internal Access Modifier in C#
The internal access modifier hides its member variables and methods from other classes and objects, that is resides in other namespace. The variable or classes that are declared with internal can be access by any member within application.
class Vehicle {
internal string Name = "Vehicle name is Car";
public void Color() {
Console.WriteLine("Vehicle color red");
}
}
class Program {
public static void Main(string[] args)
{
Vehicle v = new();
Console.WriteLine(v.Name);
Console.ReadLine();
}
}
5. Protected Internal Access Modifier in C#
The protected internal access modifier allows its members to be accessed in derived class, containing class and classes within same application.
protected internal is everything that protected is, plus also anything in the same assembly can access it.
class Vehicle {
protected internal string Name = "Vehicle name is Car";
public void Color() {
Console.WriteLine("Vehicle color red");
}
}
class Program {
public static void Main(string[] args)
{
Vehicle v = new();
Console.WriteLine(v.Name);
Console.ReadLine();
}
}
Comments
Post a Comment