find and solve || findandsolve.com
Please wait.....

Access Modifiers in C#

Access modifiers in C# are used to specify the scope of accessibility of a member of a class or type of the class itself. For example, a public class is accessible to everyone without any restrictions. Access modifiers are used to implement the encapsulation of OOP. Access modifiers allow you to define who does or who doesn't have access to certain features.


TYPES OF MODIFIER AND THEIR EXAMPLES:


C# using public modifier:

The public keyword is an access modifier, used to set the access level/visibility for classes, fields, methods, and properties.

Example:

class Car
{
public string model = "Mustang";
  {
    class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
The output:
Mustang
C# using private modifier:
If you declare a field with a private access modifier, it can only be accessed within the same class:
Example:
class Car
{
  private string model = "Mustang";
  static void Main(string[] args)
  {
    Car myObj = new Car();
    Console.WriteLine(myObj.model);
  }
}
The output:
Mustang

C# using protected modifier:

A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
Example:
     class User
     {
         protected string Name;
        {
              Console.WriteLine("Name: {0}", Name);
         }
     }
     class Program
     {
         static void Main(string[] args)
         {
             User u = new User();
             u.Name = "Suresh Dasari";
             u.GetUserDetails();
             Console.WriteLine("\nPress Enter Key to Exit..");
             Console.ReadLine();
         }
     } 

The output:
Suresh Dasari

Comments



Report Response