C# Access Modifiers

HTML
CSS
Bootstrap
JavaScript
C#
SQL
Salesforce Admin
Exercise
Study Material

Access Modifiers in C#

Access Modifiers are keywords that define the accessibility of a member, class, or datatype in a program. These are mainly used to restrict unwanted data manipulation by external programs or classes.
Why Access Modifiers?
-To control the visibility of class members (the security level of each individual class and class member).
-To achieve “Encapsulation” – which is the process of making sure that “sensitive” data is hidden from users. This is done by declaring fields as private. You will learn more about this in the next chapter.
Note: By default, all members of a class are private if you don’t specify an access modifier:
Example
class Car
{
string model; // private
string year; // private
}

Private Modifier

If you declare a field with a private access modifier, it can only be accessed within the same class:
ExampleGet your own C# Server
class Car
{
private string model = “Mustang”;
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);}}
If you try to access it outside the class, an error will occur:

Public Modifier

-If you declare a field with a public access modifier, it is accessible for all classes:

Example
class Car
{
public string model = “Mustang”;
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}

Protected

-It specifies that access is limited to the containing class or in the derived class.
class ProtectedTest
{
protected string name = “Shashikant”;
protected void Msg(string msg)
{
Console.WriteLine(“Hello ” + msg);
}
}
class Program
{
static void Main(string[] args)
{
ProtectedTest protectedTest = new ProtectedTest();
// Accessing protected variable
Console.WriteLine(“Hello “+ protectedTest.name);
// Accessing protected function
protectedTest.Msg(“Swami Ayyer”);
}
}
class ProtectedTest
{
protected string name = “Shashikant”;
protected void Msg(string msg)
{
Console.WriteLine(“Hello ” + msg);
}
}
class Program : ProtectedTest
{
static void Main(string[] args)
{
Program program = new Program();
// Accessing protected variable
Console.WriteLine(“Hello ” + program.name);
// Accessing protected function
program.Msg(“Swami Ayyer”);
}
}

Program To Practice
Practice creating static constructor and instance constructors to calculate the division and multiplication of numbers entered at run time.